Using JQuery to change a drop-down menu's selected option
How do i go about creating some JQuery code which will change the selected value of an menu.
On my page i have created a drop down menu like so:
<select id="select_Day">
<option value="Monday">Monday</option>
<option value="Tuesday">Tuesday</option>
<option value="Wednesday">Wedsnesday</option>
<option value="Thursday">Thursday</option>
<option value="Friday">Friday</option>
<option value="Saturday">Saturday</option>
<option value="Sunday">Sunday</option>
</select>
The page i have the menu on is then being passed values from a form on another page, below is how i retrieve the values:
<?php
$day = $_GET['day'];开发者_运维问答
?>
I then copy the values of the PHP variables to some javascript variables:
$(document).ready(function(event){
var day = <?php echo $day ?>;
});
How would i then change the drop-down menus selected value to that of the $day variable, so for example, if the page is passed the value 'Friday' how would i then have that option as the selected choice?
$(document).ready(function(event){
var day = <?php echo $day ?>;
$('#select_Day').val(day);
});
It is better to put selected="selected" in the html of whatever option you want to preselected then to use jQuery as it'll work even in old browsers or if javascript is turned off. You can try something like this:
<?php
$arr = array('Monday', 'Tuesday', 'Wednesday', 'Thursday','Friday','Saturday','
Sunday');
for($i = 0; $i < count($arr); $i++) {
$selected = ($arr[$i] == $day) ? 'selected="selected"' : '';
echo "<option value=\"{$arr[$i]}\" {$selected}>{$arr[$i]}</option>";
}
?>
精彩评论