1
  <select id="testSelection">
           <option> test1 </option> 
           <option> test2 </option> 
           <option> test3 </option> 
           <option> test4 </option> <--- selected this one from the pull down menu 
           <option> test5 </option> 
           <option> test6 </option> 
  </select>

             $("#testSelection").change(function()
             {
                    alert($(this).text());
             });

Strange to me, the alert message shows all the selections but I was expecting it to show on only test4 text.

Yetimwork Beyene
  • 2,239
  • 5
  • 27
  • 33
  • 1
    possible duplicate of [How to get the text of the selected option of a select using jquery?](http://stackoverflow.com/questions/1391019/how-to-get-the-text-of-the-selected-option-of-a-select-using-jquery) – j08691 Aug 22 '12 at 19:25

3 Answers3

5
<select id="testSelection">
    <option value="1">test1</option>
    <option value="2">test2</option>
    .....
</select> 

It really depends on what you want:

$("#testSelection").on('change', function() {
    // if you just want the text/html inside the select (ie: test1, test2, etc)
    alert($(this).find('option:selected').text()); 

    // or you want the actual value of the option <option value="THISHERE">
    alert($(this).val()); 
});​

jsFiddle DEMO

Mark Pieszak - Trilon.io
  • 61,391
  • 14
  • 82
  • 96
  • 1
    This is false, both methods return the value="" of the selected item. This is what you wanted to show I believe: http://jsfiddle.net/XCSgG/4/. The first val() should be text() to return the text of the selected value. The second val() will return the value of the select menu. – VVV Aug 22 '12 at 19:43
  • Thanks for noticing that! Put them in backwards like a dummy (also accidentally typed .val() up for the :selected one) – Mark Pieszak - Trilon.io Aug 22 '12 at 20:05
1

You need to use the val() function, not the text() function.

$("#testSelection").change(function()
{
    alert($(this).val());
});​
Nicholas Cardot
  • 956
  • 1
  • 11
  • 30
0

$(this).text() returns all the text within the element, in this case, the select element. That's why you get "test1 test2 ...".

Assuming you want the text of the selected option:

$(this).find(':selected').text()

If you want the value attribute of the selected option, then @mcpDESIGNS' answer will work. However, note that you need to add value attributes to your option elements, like so:

<option value="test4">test4</option>
jackwanders
  • 15,612
  • 3
  • 40
  • 40