简体   繁体   中英

Use jQuery to set select box value to first option

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?

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 . ie; waiting for the ajax response to be completed.

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

You almost got it, drop the 's' in 'options':

myElement.val(myElement.find('option').first().val());

Working jsFiddle

You could also use next code:

myElement[0].selectedIndex = 0;

This get's the Dom element (not jQuery object), works with vanilla Javascript and uses it to set the first option as the selected one based on it's index.

If you want to be sure that your option has a value and is not a placeholder you can do:

$('select option').filter( function (index, option) {
  return option.attributes.value
}).val()

That way you'll check if the HTML node has attribute value and is not empty.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM