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

javascript - How to set form option selected by value not by index - Stack Overflow

programmeradmin1浏览0评论

Here i have read how to set a form option selected by index

<select name="sel"> 
  <option value="o1">option1</option>
  <option value="o2">option2</option>
</select>

document.getElementsByName('sel')[0].selectedIndex = 0; or
document.getElementsByName('sel')[0].selectedIndex = 1;

but is it possible to set an option selected by referencing an option value instead of index?

Here i have read how to set a form option selected by index

<select name="sel"> 
  <option value="o1">option1</option>
  <option value="o2">option2</option>
</select>

document.getElementsByName('sel')[0].selectedIndex = 0; or
document.getElementsByName('sel')[0].selectedIndex = 1;

but is it possible to set an option selected by referencing an option value instead of index?

Share Improve this question edited May 23, 2017 at 11:58 CommunityBot 11 silver badge asked Feb 28, 2013 at 15:25 ViktorViktor 6334 gold badges10 silver badges27 bronze badges 0
Add a ment  | 

1 Answer 1

Reset to default 7

You could just set the value property of the <select> element, as answered in How do I programatically set the value of a select box element using javascript?

<select name="sel"> 
    <option value="o1">option1</option>
    <option value="o2">option2</option>
</select>

<select name="sel"> 
    <option value="o1">option1</option>
    <option value="o2">option2</option>
</select>

document.getElementsByName("sel")[0].value="o2";

JSFiddle

发布评论

评论列表(0)

  1. 暂无评论