5

I have a list like this:

<select name="select_list_name" id="list_id">
    <option value="">Select Option</option>
    <option value="value1">Option 1</option>
    <option value="value2">Option 2</option>
    ...
    ...
</select>

I am trying to get the text value of the currently selected option in a select list. I looked at this thread: jQuery get specific option tag text and tried this:

$("#list_id option:selected").text()

But this only gets me the first options text ("Select Option") regardless of which option has been selected.

I tried another way:

$("[name=select_list_name] option:selected").text()

That gets me the first option's text concatenated with the selected options's text ("Select OptionOption 2" if I select Option 2).

Any idea on why?

Community
  • 1
  • 1
Eqbal
  • 4,722
  • 12
  • 38
  • 47

2 Answers2

12

$('#list_id :selected').text(); should give you the selected option's text.

Something else in your code must be wrong -- this piece of code really works

Harmen
  • 22,092
  • 4
  • 54
  • 76
  • I have tried that and it behaves the same way as the first option I tried. – Eqbal Feb 28 '10 at 20:03
  • I am doing something like this: `var selectedText = $("#list_id option:selected").text();` This is within another function. Would that cause a problem? – Eqbal Feb 28 '10 at 20:23
  • No, it should not; on jsbin I pasted your code in an anonymous function. Please paste your whole function or script... – Harmen Feb 28 '10 at 20:27
  • I think there maybe an issue with another 'onChange' function being specified in the select list which is a plain javascript. I am trying to modify someone else's code. Just doing `document.form.select_list_name.options[selectedIndex].text` seems to work. – Eqbal Feb 28 '10 at 20:37
  • I found the issue. Was using the wrong id. There were two forms on the page with the same input names. – Eqbal Feb 28 '10 at 21:37
  • IMO my answer should be the correct one as I asked do you have more than one id called "list_id" – Rippo Mar 02 '10 at 18:32
  • i had the same problem and found that i needed a space after the id selector. error : $('#list_id:selected').text(); corrected : $('#list_id :selected').text(); – TGammage Oct 17 '14 at 21:48
2

This WORKS, 100%, do you have more than one id with 'list_id'?

$('#list_id :selected').text();
Rippo
  • 22,117
  • 14
  • 78
  • 117