最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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>

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>
Share Improve this question asked Jan 30, 2011 at 10:33 AlexAlex 68k185 gold badges459 silver badges650 bronze badges
Add a comment  | 

5 Answers 5

Reset to default 13

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

A bit cleaner than the other solutions:

$('#select_id').find('option:enabled:first').prop('selected',true);
$('#id-for-select option:not(:disabled):first').click()

Try this:

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

set the selected property of the option:

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

document.getElementById('value2').selected = true;
发布评论

评论列表(0)

  1. 暂无评论