簡體   English   中英

如何在JavaScript中獲取所選項目的文本?

[英]How can I get the selected item's text in 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"

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

這是你想要的:

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

這應該夠了吧。

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

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

試一試!

試試這個有效......

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM