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?
Because there is no longer an
<option/>that matches"Care Bears"in thevalueattribute.HTML defaults the
valueattribute 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