P.Brian.Mackey
P.Brian.Mackey

Reputation: 44295

How does value effect val()?

I am able to set the selected item in an html select item using jQuery's val() function. For example,

<select id="selector">
    <option></option>
    <option>Care Bears</option>
    <option>Yo Gabba Gabba</option>
</select>

<input id="selectButton" type="button" value="Care Bears" />

$('#selectButton').click(function() {
    $('#selector').val('Care Bears');//change the selected value to care bears
});

But, if I modify the code slightly,

<option value="">Care Bears</option>

val() breaks. Why is this?

Upvotes: 0

Views: 93

Answers (3)

Siva Charan
Siva Charan

Reputation: 18064

Actually it is not breaking because it checks for the value of Care Bears. Currently the value is empty.

<option value="">Care Bears</option>

Now it looks for the empty value on the list and selects that item.

That is the reason why it is selecting the empty the value.

As already told by jondavid and utku,

both are equal

<option>Care Bears</option>

<option value="Care Bears">Care Bears</option>

Upvotes: 0

jondavidjohn
jondavidjohn

Reputation: 62412

Because there is no longer an <option/> that matches "Care Bears" in the value attribute.

HTML defaults the value attribute of the <option/> tag to the Contents, if not otherwise specified.

This is actually part of the Javascript Spec as noted in the comment below.

Example to show vanilla javascript functionality

Upvotes: 2

Utku Yıldırım
Utku Yıldırım

Reputation: 2277

<option value="value">not important text</option>
when you set a value this option's value is setted.
if you dont set, its not important text will be its value

becouse

<option>Care Bears</option>
equal
<option value="Care Bears">Care Bears</option>

Upvotes: 1

Related Questions