如何在JavaScript中获取所选项目的文本?

时间:2009-09-22 15:34:30

标签: javascript

如何在JavaScript中获取所选项目的值和文本?

这是我的组合框:

<select  size="1" id="fTerminalType" name="fTerminalType">
    <option value="AP">Airport</option>
    <option value="PT">Port</option>
    <option value="BS">Bus</option>
    <option value="TR">Train</option>
</select>

我的JavaScript是这样的:

var TerminalType = document.getElementById("fTerminalType").value;

在这里,我可以获得组合框的价值。但是,如何获取所选值的文本?例如,如果值为"BS",则需要文本"Bus"

5 个答案:

答案 0 :(得分:22)

var t = document.getElementById("fTerminalType");
var selectedText = t.options[t.selectedIndex].text;

答案 1 :(得分:4)

这是你想要的:

var terminal = document.getElementById("fTerminalType");
var selectedText = terminal.options[terminal.selectedIndex].text;

这应该可以解决问题。

答案 2 :(得分:2)

function getSelectText(selId) {      
   var sel = document.getElementById(selId);
   var i = sel.selectedIndex;
   var selected_text = sel.options[i].text;
   return selected_text;
}

alert(getSelectText("fTerminalType"));

以上解释:

  • 使用传递的ID字符串获取对select的引用。
  • 获取selectedIndex并将其存储在变量中。
  • 使用selectedIndex获取所选选项的text属性。

请参阅http://www.w3schools.com/htmldom/dom_obj_select.asp

答案 3 :(得分:1)

var TerminalType = document.getElementById("fTerminalType").innerHTML;

试一试!

答案 4 :(得分:0)

试试这个有效......

    <select id="po" onchange="myFunction()">
  <option value='1'>Apple</option>
  <option>Orange</option>
  <option>Pineapple</option>
  <option>Banana</option>
</select>
<select id="po1" onchange="myFunction()">
  <option value='1'>Apple</option>
  <option>Orange</option>
  <option>Pineapple</option>
  <option>Banana</option>
</select>

<p id="demo">text1</p>
<p id="demo2">text2</p>

 <script>
function myFunction()
{

var x = document.getElementById("po").options[po.selectedIndex].innerHTML;
document.getElementById("demo").innerHTML="You selected 1: " + x;


var x1 = document.getElementById("po1").options[po1.selectedIndex].innerHTML;
document.getElementById("demo2").innerHTML="You selected 2: " + x1;
}
</script>