Chen Li Yong
Chen Li Yong

Reputation: 6107

Getting the value of form select input returns "undefined"

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

Answers (4)

Pratik Joshi
Pratik Joshi

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

hjpotter92
hjpotter92

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

Bladepianist
Bladepianist

Reputation: 490

Here, for you :

http://jsfiddle.net/jm7uo5g0/

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

Banik
Banik

Reputation: 921

you can try this also

    onchange="alert(this.value)"

Upvotes: 4

Related Questions