Justin
Justin

Reputation: 2530

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 "00: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.

Upvotes: 2

Views: 5108

Answers (4)

tkt986
tkt986

Reputation: 1028

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.

Upvotes: 0

John Hartsock
John Hartsock

Reputation: 86892

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; ?>'); 

Upvotes: 1

jon3laze
jon3laze

Reputation: 3196

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.

Upvotes: 2

zsalzbank
zsalzbank

Reputation: 9857

You want HTML:

<select id="startTime" class="startTime">

And javascript:

$("#startTime").val('<?php echo $timeStart; ?>');

Upvotes: 1

Related Questions