Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 781
polandeer Avatar asked Oct 07 '13 01:10

polandeer


People also ask

How do I select the first selection option?

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.

How do I select a default option in select tag?

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.

What is a select element?

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.

What is the use of select element?

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


1 Answers

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

like image 84
Drixson Oseña Avatar answered Sep 22 '22 18:09

Drixson Oseña