Rikard Rikard - 5 months ago 29
jQuery Question

Select options without value attr

Is this correct or invalid markup? (when the option has no value)

Is this the expected jQuery behaviour for

.val()
when there is no
value=""
assigned.

<select id="select_ID">
<option></option>
<option>Name</option>
<option>Recent</option>
</select>


If I use
$("#select_ID").val();
I get "Name"/"Recent", but if the option had a value I would get the value's content.

I know there is
.text()
to get "Name" & "Recent" in this example. Just confused why does
.val()
gives me the
.text()
when there is no value assigned.

FIDDLE (notice the different result of the alerts)

Answer

This has nothing to do with jQuery, that's how the browser handles it.

http://jsfiddle.net/jDw8N/1/

$("#select_ID").change(function () {
    var val = $("#select_ID option:selected")[0].value;
    alert(val); // somevalue or Recent
});

Ref: http://www.w3.org/TR/html5/forms.html#attr-option-value

Comments