Rikard Rikard - 4 months ago 24
jQuery Question

Select options without value attribute

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" and "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
});

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

The value attribute provides a value for element. The value of an option element is the value of the value content attribute, if there is one, or, if there is not, the value of the element's text IDL attribute.

Comments