1

Possible Duplicate:
JavaScript retrieving the text of the selected option in select element

<select name="users" onchange="showUser(this.value)">
<option value="">Select a person:</option>
<option value="1"> Option1 </option>
<option value="2"> Option2 </option>
<option value="3"> Option3 </option>
<option value="4"> Option4 </option>
</select>

From the above example, the integer value is being passed to the showUser function by the use of this.value. If instead of passing the value, I wanted to pass the contents of whatever is inside the option tag, like "Option1", how would I do this? I have tried using

showUser(this.innerHTML)

but that doesn't seem to work, or perhaps I'm approaching it incorrectly. I've looked online at options to use getElementByID but then I think I would need a unique ID for every option.

Community
  • 1
  • 1
user1152440
  • 895
  • 2
  • 13
  • 25

3 Answers3

4

You'd use:

showUser(this.selectedIndex >= 0 ? this.options[this.selectedIndex].text : '');

See the DOM2 HTML specification's documentation of HTMLSelectElement and HTMLOptionsElement.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • The above code works perfectly if I replace the double quotes "" with single quotes '' at the end. (I think this is because the onchange is already surrounded by quotes). Thank you for your reply. – user1152440 Feb 29 '12 at 16:42
2

HTML:

<select name="users" onchange="showUser(this)">
    <option value="">Select a person:</option>
    <option value="1"> Option1 </option>
    <option value="2"> Option2 </option>
    <option value="3"> Option3 </option>
    <option value="4"> Option4 </option>
</select>

javascript:

function showUser(obj){
   alert(obj.options[obj.selectedIndex].innerHTML);
}

fiddle : http://jsfiddle.net/vPhq3/1/

dku.rajkumar
  • 18,414
  • 7
  • 41
  • 58
1

In this context, this refers to the <select> element, not the selected <option>. I think you want to do showUser(this.options[this.selectedIndex].innerHTML)

Mike C
  • 3,077
  • 22
  • 29