Alex
Alex

Reputation: 68078

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>

Upvotes: 5

Views: 4653

Answers (5)

mpen
mpen

Reputation: 283345

A bit cleaner than the other solutions:

$('#select_id').find('option:enabled:first').prop('selected',true);

Upvotes: 5

user492203
user492203

Reputation:

Try this:

$('#select-id-here option:enabled').first().attr('selected', 'selected');

Upvotes: 1

Potch
Potch

Reputation: 266

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");

Upvotes: 13

GolezTrol
GolezTrol

Reputation: 116190

set the selected property of the option:

<option id="value2" value="2">2</option>

document.getElementById('value2').selected = true;

Upvotes: 0

chaos
chaos

Reputation: 124365

$('#id-for-select option:not(:disabled):first').click()

Upvotes: 1

Related Questions