【问题标题】:Get the option value in select in javascript [duplicate]在javascript中获取select中的选项值[重复]
【发布时间】:2012-08-03 10:28:01
【问题描述】:

可能重复:
How to get the selected value of dropdownlist using JavaScript?
How to get the value of a selected text in javascript

<select id="short_code">
<option value="12">First</option>
<option value="11">Second</option>
<option value="10">Third</option>
<option value="9">Fourth</option>    
</select>

我需要这样做:

if(document.getElementById("short_code").options.item(document.getElementById("short_code").selectedIndex).text)== "First")

//get the value of the option Fist , how to get the value?

【问题讨论】:

  • just asked about this。如果答案不起作用,您需要澄清您的问题而不是重新发布。

标签: javascript


【解决方案1】:
var elem = document.getElementById("short_code"),
    selectedNode = elem.options[elem.selectedIndex];

if ( selectedNode.value === "First" ) { //...

【讨论】:

  • 这不是真的你会怎么做,是吗? elem.options[elem.selectedIndex] 的处理方式很长(并且可能容易出错)。
  • 啊,对不起。我错过了这个笑话。
  • selectedNode = elem.options[elem.selectedIndex].value;
【解决方案2】:

这个怎么样:

var select = document.getElementById('short_code');
var options = select.options;
var selected = select.options[select.selectedIndex];
//which means that:
console.log(selected.value || selected.getAttribute('value'));//should log "12"
console.log(selected.innerHTML);//should log(First);

遍历所有选项(创建引用变量,就像我对options 所做的那样,或者简单的for (var i=0;i&lt;select.options.length;i++)),您可以获得所需的所有信息

【讨论】:

  • either creating a reference variable, like I did with options, or plain for - 虽然你没有使用它....
  • 不,我没有,但我将它包含在 sn-p 中只是为了展示如何引用节点列表
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-09-11
  • 2021-05-23
  • 2015-03-04
  • 1970-01-01
  • 2020-02-29
  • 1970-01-01
  • 2013-06-29
相关资源
最近更新 更多