2009-09-22 58 views
4

如何在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"

回答

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

說不上爲什麼有人給你-1,也許因爲你還沒有清理的變量名稱正確。儘管如此,對於什麼是正確的答案似乎有點苛刻。 – Steerpike 2009-09-22 15:45:48

+0

當問題首次發佈時,他的值爲第2行中的字符串。自那時起他已將其更改爲.text。 – 2009-09-22 15:46:58

+0

未正常工作 – Alex 2009-09-22 15:47:10

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字符串獲得所述選擇的參考。
  • 獲取selectedIndex並將其存儲在一個變量中。
  • 使用selectedIndex來獲取所選選項的文本屬性。

http://www.w3schools.com/htmldom/dom_obj_select.asp

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

給一個試試吧!

+0

這將獲得所有'

4

這裏是你想要的東西:

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

這應該做的伎倆。

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> 
相關問題