stackunderflow stackunderflow - 16 days ago 6
HTML Question

jQuery $.value on select > option where there is no value attribute

Given this HTML code:

<select id="menu">
<option>hi</option>
<option>bye</option>
</select>


This jQuery code:

$("#menu option").first().attr("value")


returns
hi
, even though there is no
value
attribute on the first option in the menu.

If the
<option>
has a
value
attribute, the
value
attribute is returned, as expected.

How can I have the return value of the above code be
undefined
/ something else I can identify? Or could I check if the
value
attribute is set, and only run the above code if it isn't?

Answer

Use the :not([attr]) selector:

$("#menu option:not([value])");

http://jsfiddle.net/userdude/NQm54/

I also verified that after changing, the [value] still reports as unset, so you continue to receive the same two elements without the value attribute.

$('#menu').change(function(){
  console.log($(this).val());
  console.log($("#menu option:not([value])"));
});

http://jsfiddle.net/userdude/NQm54/2/