sbeliv01
sbeliv01

Reputation: 11820

val() returning html() instead of undefined for <option> tag when no value attribute is set

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.

Upvotes: 3

Views: 551

Answers (1)

lonesomeday
lonesomeday

Reputation: 237845

This is correct, standard behaviour. In the absence of a value attribute, the textual content of the element is used as the element's value.

From the W3C website:

If there isn't [a value attribute], the value of an option element is the textContent of the element.


You can test for the presence of the content attribute using getAttribute on the DOM node:

$option[0].getAtribute('value') // returns null

Alternatively, you can use the jQuery is method with the "has-attribute" selector:

$option.is('[value]') // returns false

Upvotes: 10

Related Questions