Reputation: 6117
I have this html form code:
<form>
<select id="sex" name="sex" onchange="alert($('#sex').val())">
<option value="0">Male</option>
<option value="1">Female</option>
</select>
</form>
Maybe I use the jquery syntax to retrieve the value incorrectly, but when the select is changed, a message box show up with message "undefined". I expect the result will be either 0 or 1, or at least "Male" or "Female". Not "undefined". What have I done wrong?
https://learn.jquery.com/using-jquery-core/faq/how-do-i-get-the-text-value-of-a-selected-option/
Upvotes: 2
Views: 3432
Reputation: 11693
If you use jQuery library at the end. Their functions wont be accessible. If you see such error , there is surity that Library is included at the wrong place.
Best tip : Use/include jquery library in <head>
Upvotes: 0
Reputation: 80653
Most probably, you are loading jQuery library at the end of the page. Either include the source before form declaration or use this.value
as suggested in the other answer.
Upvotes: 4
Reputation: 490
Here, for you :
You need to add :selected after your #sex, in your $ selector :).
Like so :
<form>
<select id="sex" name="sex" onchange="alert($('#sex :selected').val())">
<option value="0">Male</option>
<option value="1">Female</option>
</select>
</form>
And do not forget to add the Jquery file ;).
Upvotes: 1