jQuery make select option 'selected'
I have a basic question regarding jQuery.
I have a static time-selection box IE:
<select name="startTime" class="startTime">
<option value="00:00:00">12:00am</option>
<option value="00:15:00">12:15am</option>
<option value="00:30:00">12:30am</option>
<option value="00:45:00">12:45am</option>
etc...
</select>
So when I run my MySQL Query I pull a date from the database, and I want to make a specific time frame selected
my database returns a value such as, "00:30:00" date(H:i:s) So I need to make "0开发者_如何学C0:30:00" the selected value with jQuery, and i'm not exactly sure how to make that happen.
I thought it was something like this:
$(".startTime").val('<?php echo $timeStart; ?>');
Perhaps someone could shed some light.
Here is a handy cheatsheet for jQuery and Select elements: cheatsheet If you are going to be working with them it'll come in handy.
First you should use the element tag name in the selector for efficiency
$("select.startTime")
Second you should check what the value of <?php echo $timeStart; ?>
is, because the following should work.
$("select.startTime").val('<?php echo $timeStart; ?>');
You want HTML:
<select id="startTime" class="startTime">
And javascript:
$("#startTime").val('<?php echo $timeStart; ?>');
If you want to change the selected item on page load, you could try some thing like this.
<script type="text/javascript">
$(document).ready(function(){
<?php
$your_query_return="00:15:00";
?>
$('select.startTime').val("<?php echo your_query_return;?>").attr('selected','selected');
});
</script>
If you put the script above on your head tag of the page, it should work. The same procedure can give you same result even you if you want to use ajax.
精彩评论