Alex
Alex

Reputation: 1963

How can I get the selected item's text in JavaScript?

How can I get the selected item's value and text in JavaScript?

This is my combobox:

<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 is like this:

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

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

Upvotes: 6

Views: 69032

Answers (6)

marlar
marlar

Reputation: 4135

A modern one-liner:

document.getElementById("fTerminalType").selectedOptions[0].text

selectedOptions returns an array of the selected options. In a dropdown there will be only one (index 0), but for a listbox with the multiple attribute there can be more than one.

Upvotes: 0

Kulwinder Singh
Kulwinder Singh

Reputation: 1

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>

Upvotes: 0

karim79
karim79

Reputation: 342635

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

  • get a reference to the select using the passed ID string.
  • get the selectedIndex and store it in a variable.
  • use the selectedIndex to get the text property of the selected option.

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

Upvotes: 2

Eric Ryan Harrison
Eric Ryan Harrison

Reputation: 749

Here is what you want:

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

That should do the trick.

Upvotes: 4

brettkelly
brettkelly

Reputation: 28205

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

give that a try!

Upvotes: 1

D&#39;Arcy Rittich
D&#39;Arcy Rittich

Reputation: 171401

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

Upvotes: 32

Related Questions