views:

710

answers:

3

Hello,

I'm currently using jQuery to return some JSON results. Once these results are returned, I'm using them to pre-populate fields in my form.

However, I need some help in pre-selecting items in a drop down box. For example, I have a select box (this is shortened):

<select id="startTime">
<option value="14:00:00">2:00 pm</option>
<option value="15:00:00">3:00 pm</option>
<option value="16:00:00">4:00 pm</option>
<option value="17:00:00">5:00 pm</option>
<option value="18:00:00">6:00 pm</option>
</select>

And if my JSON value is:

 var start_time = data[0].start  // Let's say this is '17:00:00'

How can I, using jQuery, make the option with value '17:00:00' selected?

 <option value="17:00:00" selected="selected">5:00 pm</option>
+2  A: 
$('#startTime').val(start_time);
cballou
+2  A: 

It's just $("#startTime").val(start_time);

JacobM
+7  A: 
$('option[value=17:00:00]').attr('selected', 'selected');
or 
$('option[value='+ data[0].start +']').attr('selected', 'selected');
Sam Hasler
Exactly what I was looking for. Thanks.
Dodinas
Good answer. I would probably also recommend accounting for which selection box like so: $('#mySelect option[value="17:00:00"]').attr('selected','selected');
Volomike