Get text of the selected option with jQuery
JavascriptJqueryHtmlDrop Down-MenuJquery SelectorsJavascript Problem Overview
I have a select box with some values. How do I get the selected options text, not the value?
<select name="options[2]" id="select_2">
<option value="">-- Please Select --</option>
<option value="6" price="0">100</option>
<option value="7" price="0">125</option>
<option value="8" price="0">150</option>
<option value="9" price="0">175</option>
<option value="10" price="0">200</option>
<option value="3" price="0">25</option>
<option value="4" price="0">50</option>
<option value="5" price="0">75</option>
</select>
I tried this:
$j(document).ready(function(){
$j("select#select_2").change(function(){
val = $j("select#select_2:selected").text();
alert(val);
});
});
But it's coming back with undefined
.
Javascript Solutions
Solution 1 - Javascript
Close, you can use
$('#select_2 option:selected').html()
Solution 2 - Javascript
$(document).ready(function() {
$('select#select_2').change(function() {
var selectedText = $(this).find('option:selected').text();
alert(selectedText);
});
});
Solution 3 - Javascript
Change your selector to
val = j$("#select_2 option:selected").text();
You're selecting the <select>
instead of the <option>
Solution 4 - Javascript
Also u can consider this
$('#select_2').find('option:selected').text();
which might be a little faster solution though I am not sure.
Solution 5 - Javascript
You could actually put the value = to the text and then do
$j(document).ready(function(){
$j("select#select_2").change(function(){
val = $j("#select_2 option:selected").html();
alert(val);
});
});
Or what I did on a similar case was
<select name="options[2]" id="select_2" onChange="JavascriptMethod()">
with you're options here
</select>
With this second option you should have a undefined. Give me feedback if it worked :)
Patrick