Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery / Programmatically Select an Option in Select Box

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> 
like image 325
Dodinas Avatar asked Oct 15 '09 17:10

Dodinas


People also ask

How do you select a particular option in a select element in jQuery?

Syntax of jQuery Select Option$("selector option: selected"); The jQuery select option is used to display selected content in the option tag. text syntax is below: var variableValue = $("selector option: selected").

How do you check if any option is selected in jQuery?

Use the jQuery: selected selector in combination with val () method to find the selected option value in a drop-down list.

How do you append to a select option?

Method 1: Append the option tag to the select boxThe select box is selected with the jQuery selector and this option is added with the append() method. The append() method inserts the specified content as the last child of the jQuery collection. Hence the option is added to the select element.


2 Answers

update:

As of jQuery 1.9, jQuery has updated this functionality. The "selected" state of an option is actually a property, therefore jQuery has changed this to use the .prop() method. Syntax is very similar and easy to switch:

$('#startTime option[value=17:00:00]').prop('selected', true); 

See http://api.jquery.com/prop/#entry-longdesc for why it needs to pass true.


Older jQuery

$('#startTime option[value=17:00:00]').attr('selected', 'selected'); 

or

$('#startTime option[value='+ data[0].start +']').attr('selected', 'selected'); 
like image 194
Sam Hasler Avatar answered Sep 28 '22 16:09

Sam Hasler


$('#startTime').val(start_time); 
like image 26
Corey Ballou Avatar answered Sep 28 '22 17:09

Corey Ballou