Consider the following HTML:
<select>
<option value="hasAttr">Has a value attr</option>
<option>Does not have a value attr</option>
</select>
As you can see, one of the options has a value attribute set and the other does not. However, when I go to check the val() for each of the options via jQuery, the option that does not have a value attribute set is returning the text inside of the tag (html()) instead of undefined as I would normally expect.
var $select = $('select');
$select.each(function() {
var $this = $(this),
$options = $this.children('option');
$options.each(function(){
var $option = $(this),
$value = $option.val(),
$html = $option.html();
console.log('Option Value: '+ $value +'\nOption HTML: '+ $html);
});
});
Even if I change the code to look for $option.attr('value'), I still get the same results. Is there a way that I can check to see if an <option> has a value attribute present that will return boolean?
Here is a jsFiddle.
Updated jsFiddle with solution.
This is correct, standard behaviour. In the absence of a
valueattribute, the textual content of the element is used as the element’s value.From the W3C website:
You can test for the presence of the content attribute using
getAttributeon the DOM node:Alternatively, you can use the jQuery
ismethod with the “has-attribute” selector: