【问题标题】:How to set form option selected by value not by index如何设置按值而不是按索引选择的表单选项
【发布时间】:2013-02-14 20:45:41
【问题描述】:

Here我已经阅读了如何设置索引选择的表单选项

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

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

【问题讨论】:

    标签: javascript forms dom select set


    【解决方案1】:

    您可以设置&lt;select&gt; 元素的value 属性,如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

    【讨论】:

    • 没错。如果您只是 alertconsole.log 语句,您将看到它返回值(在本例中为 o2)。另外,考虑到selected 属性将应用于&lt;option&gt; 元素,而不是&lt;select&gt;。例如,这会起作用:document.getElementsByName("sel")[0].options[1].setAttribute("selected", "selected");
    • ^^这与 .selectedIndex=1;不是吗?
    • 确实如此。您可以使用selectedIndex 属性按索引或使用value 属性按值设置所选选项。
    • 啊啊啊啊!好的!我知道了!非常非常非常非常非常感谢!
    • 对不起,因为我没有足够的声望点,所以无法投票赞成你的答案...
    猜你喜欢
    • 2021-03-08
    • 2015-02-14
    • 2012-10-31
    • 1970-01-01
    • 2014-10-15
    • 1970-01-01
    • 1970-01-01
    • 2013-03-01
    • 1970-01-01
    相关资源
    最近更新 更多