javascript 如何设置按值而不是索引选择的表单选项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15139281/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 23:39:18  来源:igfitidea点击:

How to set form option selected by value not by index

javascriptformsdomselectset

提问by Viktor

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

但是是否可以通过引用选项值而不是索引来设置选择的选项?

回答by Xavi López

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

您可以只设置元素的value属性<select>,如如何使用 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

JSFiddle