tags:

views:

212

answers:

4

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

+1  A: 
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%5Fobj%5Fselect.asp

karim79
+4  A: 
var t = document.getElementById("fTerminalType");
var selectedText = t.options[t.selectedIndex].text;
RedFilter
Dunno why someone gave you -1, maybe 'cause you hadn't cleaned the variable names up properly. Still, seems a bit harsh for what's otherwise the right answer.
Steerpike
When the question was first posted, he had .value as the string in line 2. He has changed it to .text since then.
Eric Ryan Harrison
its not working
Alex
+1 for correct use of the option element's text property: http://www.w3.org/TR/2000/WD-DOM-Level-1-20000929/level-one-html.html#ID-70901257
NickFitz
@Alex: "its not working" isn't going to help anybody help you. What isn't working? In what way does it fail? How have you tested it? Does it fail on all browsers or just some?
NickFitz
here 'e'is undefind error
Alex
@Alex: looks like you may have tested it when it said ".value" instead of ".text" - if you try the edited version it should work. It just worked for me on IE 6, FF 3.5 and Chrome 3 :-)
NickFitz
A: 
var TerminalType = document.getElementById("fTerminalType").innerHTML;

give that a try!

inkedmn
That gets the html for all the `<option>` elements!
Crescent Fresh
+2  A: 

Here is what you want:

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

That should do the trick.

Eric Ryan Harrison