How to get selected element text in JavaScript?

How can I get the selected element value and text in JavaScript?

This is my summary:

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

My JavaScript looks like this:

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

Here I can get the combobox value. But how can I get the text of the selected value? For example, if the value was "BS" , I need the text "Bus" .

+4
source share
5 answers
 var t = document.getElementById("fTerminalType"); var selectedText = t.options[t.selectedIndex].text; 
+21
source

Here is what you want:

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

That should do the trick.

+4
source
 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")); 

The above:

  • Get a selection link using the passed ID string.
  • get selectedIndex and save it in a variable.
  • use the selectedIndex value to get the text property for the selected parameter.

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

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

give a try!

+1
source

Try this, it works ......

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

All Articles