leora
leora

Reputation: 196449

How to select an entry in a combobox using jquery?

I have a HTML combobox which has two entries. One is blank and the other is some text. I don't know what the values are.

Is there anyway by using jquery (given the constaint above) that I can have the entry with text in it programtically selected in the combobox?

Upvotes: 0

Views: 588

Answers (4)

Tz_
Tz_

Reputation: 2949

Pure JQuery selector that selects the first non-empty option (based on the text of the option):

$('#myDropDown option:not(:empty):first')

Using the following sample:

<select size="5" id="foobar">
    <option value="emptyoption"></option>
    <option value="bar">bar</option>
</select>

This selects the "bar" option:

$('#foobar option:not(:empty):first').prop('selected',true);

Upvotes: 0

Tomalak
Tomalak

Reputation: 338128

This selects the first non-empty option:

$("#mySelectBox").val(function() {
  for (var i = 0; i<this.options.length; i++) {
    if (this.options[i].text != "") return this.options[i].value;
  }
});

You could do $.trim(this.options[i].text) if the text can contain white-space.

It's a generalized solution, if you are sure that you always want to select the second option, a simpler method exists, of course - see mcgrailm's answer.

Upvotes: 1

mcgrailm
mcgrailm

Reputation: 17640

this is one way to do it

assuming this is the html

<select size="5" id="foobar">
   <option value="">foo</option>
    <option value="bar">bar</option>
</select>

here is the jquery

$('#foobar option:nth-child(2)').prop('selected',true);

here is a working demo

Upvotes: 1

Matthew Riches
Matthew Riches

Reputation: 2286

How about sorting the list:

$("#combo").html($("#combo option").sort(function (a, b) {
    return a.text == b.text ? 0 : a.text < b.text ? -1 : 1
}));

But out of interest, why doesn't the option have the selected value - is it created dynamically?

Upvotes: 0

Related Questions