Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use jQuery to set select box value to first option

Tags:

I am dynamically populating a select box with options. When I do this, I want the value of the select box to be the value of the first option (a 'default option', if you like). Sounds really simple, but I just can't get it to work.

var myElement = $('select[name="myName"]'); 

.... tried the following three variations

// myElement.find('option').first().prop('selected', 'selected'); // myElement.val(myElement.find('options').first().val()); myElement.prop('selectedIndex', 0); 

...but the following line gives a blank alert

alert(myElement.val()); 

Where am I going wrong?

like image 598
DatsunBing Avatar asked Aug 23 '13 00:08

DatsunBing


1 Answers

options should be option

myElement.find('option:eq(0)').prop('selected', true); 

You can use the eq selector on the option to select the first option.

If you know the value of the first option. Then you could simply do

myElemeent.val('first value') // Which selects the option by default 

The 2nd case you tried should work, unless you are not calling at the right point . i.e; waiting for the ajax response to be completed.

Try calling that inside the done or the success (deprecated) handler

like image 60
Sushanth -- Avatar answered Nov 13 '22 06:11

Sushanth --