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)?
Select first element of <select> element using JQuery selector. Use . prop() property to get the access to properties of that particular element. Change the selectedIndex property to 0 to get the access to the first element.
The option tag contains the value that would be used when selected. The default value of the select element can be set by using the 'selected' attribute on the required option. This is a boolean attribute. The option that is having the 'selected' attribute will be displayed by default on the dropdown list.
The select element represents a control for selecting amongst a set of options. The multiple attribute is a boolean attribute. If the attribute is present, then the select element represents a control for selecting zero or more options from the list of options.
Definition and Usage The <select> element is used to create a drop-down list. The <select> element is most often used in a form, to collect user input. The name attribute is needed to reference the form data after the form is submitted (if you omit the name attribute, no data from the drop-down list will be submitted).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With