polandeer
polandeer

Reputation: 396

Select the first enabled option in a select element

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)?

Upvotes: 7

Views: 5512

Answers (1)

Drixson Ose&#241;a
Drixson Ose&#241;a

Reputation: 3641

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

Upvotes: 10

Related Questions