Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .val() is returning .text() not .val()

Tags:

jquery

I have this code

<select id="month">
    <option val='0'>January</option>
    <option val='1'>February</option>
</select>

I'm using this to try to get the values:

$month = $("#month option:selected").val();

But it's returning the text "January" and "February" not "0" or "1"

I tried this and got the same results:

$month = $("#month").val();
like image 705
Wil Wells Avatar asked Apr 04 '14 21:04

Wil Wells


People also ask

What does VAL () return in jQuery?

jQuery val() Method The val() method returns or sets the value attribute of the selected elements. When used to return value: This method returns the value of the value attribute of the FIRST matched element.

Does val () return a string?

val()Returns: String or Number or Array. Description: Get the current value of the first element in the set of matched elements.

What does VAL () do?

There are two usage of jQuery val() method. It is used to get current value of the first element in the set of matched elements. It is used to set the value of every matched element.

What is the difference between Val and value in Javascript?

attr('value') returns the value that was before editing input field. And . val() returns the current value.


1 Answers

The attribute should be value, not val:

<option value='0'>January</option>
<option value='1'>February</option>

When an option doesn't have a value attribute, the text is used as the default.

like image 159
Barmar Avatar answered Sep 23 '22 19:09

Barmar