Ok, so here is my code. I am trying to select a picklist value using Javascript, from PHP (I do not want a direct method to do this with PHP, as this won't work for my particular program)
Here's the code:
ECHO '<script type="text/javascript">
var pl = document.getElementById("cultpicklist");
pl.options[37].selected = true;
</script>';
However when I try to run this, it does not seem to work and it says pl.options[37] is undefined.
What am I doing wrong?
Note, there is a multiple select list which has an option with a value of 37.
EDIT: I seem to get this error or warning message:
Element referenced by ID/NAME in the global scope. Use W3C standard document.getElementById() instead.
admin.php?org=7()admin.php?org=7 (line 68)
pl.options[37].selected = true;
Here's the relevant HTML:
<fieldset><label for="culture">Culture:</label>
<select name="culture[]" multiple="multiple" id="cultpicklist"><?php
while ($cultrow = mysql_fetch_array($rescult)) {
ECHO '<option name="culture[]" value="'. stripslashes($cultrow['cult_id']) .'">'. stripslashes($cultrow['cult_desc']) .'</option>';
}
?>
</select></fieldset>
Here's the generated HTML code:
<select id="cultpicklist" multiple="multiple" name="culture[]">
<option value="36" name="culture[]">test1</option>
<option value="37" name="culture[]">test2</option>
<option value="38" name="culture[]">test3</option>
<option value="39" name="culture[]">test4</option>
</select>
The index of the options IS NOT the value of the option. When you use pl.options[37] you saying to JS to get the thirty-seventh option in the select and not the option with the value 37.
Try this:
<script type="text/javascript">
var pl = document.getElementById("cultpicklist");
for(var i=0; i<pl.options.length;i++) {
if(pl.options[i].value == "") { // Between the quotes you place the comparison value!
pl.options[i].selected = true;
}
}
</script>
BTW: If you already use jQuery on your page it's more correct to use it's functions, but if you don't use jQuery is too much code to add to your page just to change a select value.
You are likely putting the cart before the horse. You cannot use JavaScript to manipulate DOM elements until they've been rendered in the browser.
Put your script AFTER your HTML or check to see of the DOM is ready before running your script.
Why not use JQuery first of all...
$('#cultpicklist').val('myvaluetoselect');
Is MUCH easier to code, read and works instead of using bulky old school javascript...
Using jQuery, you could still put your code in between <head></head> tags. You would use $(document).ready() thus executing your code after the whole document has rendered.
Related
I would like to add a small code snip to check out whether an option is selected
This usually is easily done if the page is html, now my code snip looks something like this
echo "<td>Language</td>";
echo "<td><select id='language' name='language'>
<option value=''>Select...</option>
<option value='en_US'>English(US)</option>
<option value='en_AU'>English(AU)</option>
<option value='en_UK'>English(UK)</option>
</select><span id="info"></span>
</td>";
if it is html
<script>
$('#language').change()
{
if('Select...'==$('#language').text())
{
$('#info').html("Please select a value...");
}
}
</script>
[UPDATE]
I would like to add that the above php source code used to generate html code is put in a form tag that is
echo "<form action='checkdb.php' method='POST'>
// all above and more
</form>"
the page checkdb.php used the posted data to update database.
How can I add in the jquery code piece as mentioned in the current file (the file with the html code is being generated) ? I am thinking as people once told me that javascript can't be called in the middle of the php execution and I wonder if I may need to use ajax get function. Please offer some help. Thank you.
// Listen, and respond to, the change even on our select
$("#language").on("change", function(e){
// Set the html content of our info element
$("#info").html(function(){
// If the selected option has no value, ask to select a value
return e.target.value === "" ? "Please select a value." : "" ;
});
// Trigger upon page load
}).trigger("change");
Demo: http://jsbin.com/owaqaz/2/edit
Note the last line, $.trigger("change") - this will cause the page to immediately populate the #info element if the select element currently has no value.
Change your jQuery to:
$('#language').change(function() {
if ('Select...' == $('#language option:selected').text()) {
$('#info').html("Please select a value...");
}
});
jsFiddle example.
Update: Or a more brief version:
jQuery:
$('#language').change(function() {
$('#info').html(('Select...' == $('#language option:selected').text()) ? "Please select a value...":"");
});
jsFiddle example.
Sorry but what was your question?
A PHP page turns into a HTML Page after processing (a user never sees the PHP source code), and you can easily use javascript to check for the value.
Ok... First off, I know this isn't a new question.
But, for some reason none of the suggestions Google has found for me (dating back to the begining of time even) are working. So, please bear with me.
Let's say, I have a script structured something like this:
<?php
try {
print "<table><form id='menu' action='index.php' method='POST'><tr>";
print "<td>Select A Fruit</td><td><select name=fruit>
<option value=''></option>
<option value='apple'>Apple</option>
<option value='orange'>Orange</option>
<option value='pear'>Pear</option></select></td></tr>";
print "<tr><td><input type='submit' name='submit' value='Submit'></td></tr></form></table>";
if (isset($_POST['submit'])){
if (!empty($_POST['fruit'])){
//Do whatever the form is supposed to trigger.
}
else {
//Nothing selected; handle however makes sense.
}
}
}
catch(Exception $e) {die( print_r( $e->getMessage() ) );}
?>
And instead of using the button, I want it to submit the form as soon as an option is selected.
Based on my searches, the textbook answer appears to be to modify the Select tag with an onchange attribute calling a JavaScript method like so:
<select name='fruit' onchange='document.getElementById('menu').submit()'>
or the short form:
<select name='fruit' onchange='this.form.submit()'>
But here is where I'm stuck...
None of the posts I found explain where you tell the browser/interpreter to drop out to JavaScript to make that work. So, this change does nothing for me.
What am I missing here?
I would get away from the dom level 0 handler and set the select's onchange handler to a function that grabs your form, and calls submit on it.
document.getElementById("yourSelectId").onchange = function() {
document.forms["formsId"].submit();
};
I'm showing you a more robust way of adding event handlers to dom elements. Instead of saying onchange="blah()" you can set up a body onload function that'll run when your dom is ready, then you can use JavaScript to add your handlers:
<body onload="init()">
function init() {
document.getElementById("yourSelectId").onchange = function() {
document.forms["formsId"].submit();
};
}
Or, you can skit the ugly <body onload="init()"> altogether and just put the code
document.getElementById("yourSelectId").onchange = function() {
document.forms["formsId"].submit();
};
in a regular script block at the bottom of your body
Your markup isn't valid, a table-element cannot have a form as child-element(wrap the form around the table)
Choose another name for the submit-button, otherwise you will receive an error in IE when calling submit()
I would suggest using an event listener rather than adding the attribute to your code. Also, it is recommended to have the static page display the submit button, and simply remove it via javascript after the page loads.
element.addEventListener Example
<script type="text/javascript">
document.getElementById("yourSelectId").addEventListener("change", function(){document.forms["yourFormId"].submit();});
</script>
To read more about element.addEventListener (esp. to see why it's important to use it), check out the article on element.addEventListener at MDN.
How javascript works in onchange attribute
But here is where I'm stuck... None of the posts I found explain where you tell the browser/interpreter to drop out to JavaScript to make that work. So, this change does nothing for me.
Attributes such as onchange, onclick, etc (notice "on" at the beginning) parse the value as javascript. Ergo, that is where you are telling the browser to use javascript to make it work :)
I have two select box and the second select box value is dependent on the first select box. So basically what I am trying to do is that after a user makes a selection on the first select box, it will then store this value of the first select box as a variable. Then it will query my database to populate the second select box, based on the first selected value. Question is, how do I pass in the var I have in the first select box to PHP? I've read other post and people said it's impossible, but if it is then how do people do this? AJAX?
If I understand correctly, then yes, using AJAX is really your only choice.
Indeed, you can, with AJAX, call something like 'getSelectionData.php?data=' + select1.value, which returns a JSON array of data based on the selection in the first select box. You then parse the data and enter it into the second select box.
Add a onchange event listener to the first select box:
document.getElementById("select1").addEventListener("change", function(ev){
var yourstoredvariable = this.value;
someFunctionThatCallsAjax(yourstoredvariable);
}, true);
I assume that you have a Country/City dropdowns, You can do it in two ways, the good AJAX way and the bad way (refresh page on change), I'm gonna describe the good way in jQuery, or at least what I see it good.
this is the client-side (i.e. client) code:
<select id="country">
<option value="1">Canada</option>
<option value="2">UK</option>
</select>
<select id="city" disabled="disabled"></select>
<script type="text/javascript">
$('#country').change(function(){
$('#city').load('/ajax-city.php', {id: $(this).val()});
});
</script>
This is the ajax-city.php code (server):
<?php
$countryId = $_REQUEST['id'];
$cities = array(); // Get it from db, using mysql_query or anything you want to use
foreach($cities as $city) {
echo "<option id=\"{$city['id']}\">{$city['name']}</option>";
}
PS. you would need to include jQuery in your html code, and of course put the two files in the same directory (or change the $.load path).
This particular code is not tested, I've just written it. But it usually works fine to me this way.
You will have an onchange event on the first <select> that will query the server using Ajax with the value of the selected <option> that will return the <option> elements with which to populate the 2nd <select> element.
Question is, how do I pass in the var I have in the first select box to PHP?
I see no problem here.
Just usual, an ordinary html form using GET method.
What's so big about it?
If I see correct you're using Jquery. So you can do this like this:
$('#idOfSelectBox1').change(function(){
jQuery.ajax({
type: "GET",
url:"yourdomain.com/script.php",
data:"selectBox:'"+$('#idOfSelectBox1').val()+"'",
success:function(result){
//do smth with the returned data
}
});
});
in the script.php do your magic and echo what you want to pass back to js
I am using PHP to generate dynamic dropdown, the dropdown list items are fetched from database.
Here's the php code for that and it works.
<select name="title[]" id="title">
<?php $categories = Category::find_by_cid(5); foreach($categories as $category): ?>
<option value="<?php echo $category->name; ?>"><?php echo $category->name; ?></option>
<?php endforeach; ?>
</select>
What i want to do is, Using jQuery whenever a link with id AddNew is clicked, a new dropdown should appear below that, containing same values.
Also, is there any way to execute php code inside javascript??
ex :
<script>
var name = "<?php echo $user->name; ?>";
</script
To clone elements, you can use jQuery's .clone() method (obviously):
$('#addNew').click(function() {
$('select.title').after($('select.title').clone());
});
Note that ID's should be unique on the page, if you are going to clone the select element, give it a class instead of ID.
And yes, you can "use" PHP in JavaScript, provided that the file is processed with PHP. Just note that you are not actually accessing PHP with JavaScript, but rather creating JavaScript files dynamically.
Use jQuery .clone() method.
Also, is there any way to execute php code inside javascript??
Not really, no. PHP is executed server-side, so in the example you provided:
<script>
var name = "<?php echo $user->name; ?>";
</scrip>
That will turn out to be:
<script>
var name = "Josh";
</script>
at run-time, when the javascript has access to it. The php code is executed, then rendered to html where the javascript finally sees it. What you are doing is dynamically creating javascript rather than executing php code.
** EDIT **
I'm afraid I wasn't in the right direction - the problem isn't what I asked about.
the Javascript works as it should, it's the PHP that doesn't show what I want it to
on the first "run" - and I'm stil not sure why.
Sorry for somewhat wasting your time...
**
I have a form that might or might not already contain data in its fields.
If a user reaches the form and he already has some data in the system,
his ID number, for instance, will appear in the ID field - and a JavaScript function running
onLoad will disable the input field and change its style:
<body onload="runFunction()">
the problem is that it seems to run before the PHP does its part,
and only if I refresh the page, the JS function does everything I want it to
(it disables and styles some other form fields that depend on a PHP condition).
Is there a way to have this JS function run AFTER the page was rendered?
I tried running this before closing the page:
<body>
...
...
<script>
runFunction();
</script>
</body>
</html>
but to no avail.
any ideas?
Thanks!
some of the relevant PHP code: [I removed id attributes to make reading easier]
<?php if ($h_phone != '' && $h_phone_pre != '') {
echo "<td class=\"input\"><input type=\"text\" id=\"new_user_home_tel\" value=\"$h_phone\" size=\"8\" maxlength=\"7\" disabled=\"disabled\" /> -
<select id=\"new_user_home_tel_pre\" disabled=\"disabled\">
<option value=\"$h_phone_pre\" selected=\"selected\"></option>";
} else {
echo '<td class="input"><input type="text" id="new_user_home_tel" size="8" maxlength="7" /> -
<select id="new_user_home_tel_pre">
<option value=" " selected="selected"></option>';
}?> <option value="02">02</option>
<option value="03">03</option>
<option value="04">04</option>
<option value="08">08</option>
<option value="09">09</option>
</select>
</td>
the Javascript code just changes the style if the field isn't empty and that works,
but the PHP works only after a refresh.
Your Javascript does run after the page is loaded, the problem is elsewhere.
It must be that your server sends different HTML before and after refresh. I suggest that if you save the source of the page you get first time and compare it with the source you get after refresh. I bet you will spot the difference and that will tell you what is wrong.
JQuery does this. Anything inside the following will execute once the page is rendered:
$(document).ready(function() {
//Call your function here
});
Try the "defer" attribute.
One way is to output-buffer the page in PHP. That means everything generated goes into memory until the script finishes running and then it's all sent out at once.
Take a look at http://uk.php.net/ob_start
the non JS library answer is:
<script>
window.onload = function(){
/* do stuff */
}
</script>
However using a JS library like JQuery will take care of all those niggle cross browser bug/problems.
Your right to place your <script> blocks at the end of you body. This improves page load performance as the browser blocks when it hits a <script> block.
Definitely hacky, but you could always put a 2x2 transparent image below your form and run the function using it's onLoad. I did a similar thing on a conditionally included file so there were no errors in the case that the file wasn't included.
I'd suggest that you add your content to an output variable and than echo it at the end of the file. Ex:
...
$output .= '<body onload="runFunction();">';
while(...)
{
$output .= '...';
}
$output .= '</body>';
...
echo $output;
I'm afraid I wasn't in the right direction - the problem isn't what I asked about. the Javascript works as it should, it's the PHP that doesn't show what I want it to on the first "run" - and I'm stil not sure why. Sorry for somewhat wasting your time...
I know this is really late for this post, but the reason this isn't working is that PHP renders HTML and then you can't interact with it again (unless you can do some snazzy AJAX stuff). Point being that the JS works fine bc it is client side, PHP doesn't work bc it is server side. Hope that helps anyone else who comes here!