Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - set the value of a select to one of its options

How can I set the value of a select input field to the value of the first option that is not disabled

for eg., in this field, the selected value is 1. How can I change this value to the next non-disabled option, ie. 2 ?

<select>
  <option disabled="disabled" value="1">1</option
  <option value="2">2</option
  <option disabled="disabled" value="3">3</option
  <option value="4">4</option
</select>
like image 956
Alex Avatar asked Jan 30 '11 10:01

Alex


People also ask

How do you select a particular option in a select element in jQuery?

Syntax of jQuery Select Option$("selector option: selected"); The jQuery select option is used to display selected content in the option tag. text syntax is below: var variableValue = $("selector option: selected").

How do you set the value of select?

Use the value property to set the value of a select element, e.g. select. value = 'new value' . The value property can be used to set or update the value of a select element. To remove the selection, set the value to an empty string.


2 Answers

for your given example, I would use:

$("select option:not([disabled])").first().attr("selected", "selected");

if your select had a specific ID ("#foo" for example):

$("#foo option:not([disabled])").first().attr("selected", "selected");

like image 182
Potch Avatar answered Sep 24 '22 20:09

Potch


A bit cleaner than the other solutions:

$('#select_id').find('option:enabled:first').prop('selected',true);
like image 23
mpen Avatar answered Sep 26 '22 20:09

mpen