Using jQuery 1.6.2
HTML that I'm operating on
<select id="langId">
<option value="0">Argentina - Spanish</option>
<option value="1">Brazil - Brazil English</option>
</select>
I need to get the string of the selected value (ie: "Brazil - Brazil English")
What I am currently using:
var langVal = $('#langId option[value="' + $('#langId').val() + '"]').contents();
This works to a point. It gives me something like ["Brazil - Brazil English"]
which I can access at langVal[0]
If I do console.log(langVal[0])
then I get what I am looking for "Brazil - Brazil English"
, but if I do something like console.log(("The value is: " + langVal[0]));
then what I see is The value is: [object Text]
I have no idea what is causing this [object Text]
to show up instead of my value. I've tried the toString() method, but it doesn't help.
The end goal is to get the text value of the selected object into a cookie. The numerical value attribute on the option elements must remain the same.
Instead of using
$('#langId option[value="' + $('#langId').val() + '"]').contents()
you want to use$('#langId option[value="' + $('#langId').val() + '"]').html()
or$('#langId option[value="' + $('#langId').val() + '"]').text()
The contents function actually creates a new jQuery object -- not the text value you want.
That will get you the text of the currently selected option in your select list.