Reputation: 44295
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
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
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
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