admin管理员组

文章数量:1297094

How could I set the value of a select element to the first enabled option? Say I have html like this:

<select name="myselect" id="myselect">
    <option value="val1" disabled>Value 1</option>
    <option value="val2">Value 2</option>
    <option value="val3" disabled>Value 3</option>
    <option value="val4">Value 4</option>
</select>

How could I select the first option which isn't disabled (here it would be val2)?

How could I set the value of a select element to the first enabled option? Say I have html like this:

<select name="myselect" id="myselect">
    <option value="val1" disabled>Value 1</option>
    <option value="val2">Value 2</option>
    <option value="val3" disabled>Value 3</option>
    <option value="val4">Value 4</option>
</select>

How could I select the first option which isn't disabled (here it would be val2)?

Share Improve this question asked Oct 7, 2013 at 1:36 polandeerpolandeer 3964 silver badges17 bronze badges 4
  • Are the select options dynamically generated? – Lloyd Banks Commented Oct 7, 2013 at 2:11
  • Most browsers would do this automatically wouldn't they? (Chrome, FF, and IE10 do.) – nnnnnn Commented Oct 7, 2013 at 2:34
  • @LloydBanks Assume the select options are dynamically generated on the server side. – polandeer Commented Oct 8, 2013 at 1:16
  • @nnnnnn Assume the disabled attribute could change. – polandeer Commented Oct 8, 2013 at 1:17
Add a ment  | 

1 Answer 1

Reset to default 10

Try this selecting the first option that is enabled.

$('#myselect').children('option:enabled').eq(0).prop('selected',true);

.children() for finding the list of option that is enabled , .eq(0) choosing the first entry on the list and using .prop() to select the option

本文标签: javascriptSelect the first enabled option in a select elementStack Overflow