DatsunBing
DatsunBing

Reputation: 9076

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?

Upvotes: 24

Views: 84329

Answers (4)

Nima Izadi
Nima Izadi

Reputation: 1004

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.

Upvotes: 0

Marin Bînzari
Marin Bînzari

Reputation: 5348

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.

Upvotes: 5

Yotam Omer
Yotam Omer

Reputation: 15356

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

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

Working jsFiddle

Upvotes: 6

Sushanth --
Sushanth --

Reputation: 55750

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

Upvotes: 38

Related Questions