I have a select list like so:
<select id="drpColours">
<option value="" selected="selected">Choose color</option>
<option value="1">black</option>
<option value="2">BLUE</option>
</select>
I can I set the selected item based on the text item and not the v开发者_JS百科alue. So if i pass "Blue" to a function, I want the function to set the 3rd item in the list to be selected.
I am using jquery for this.
Try this:
function setColor( color ) {
$('#drpColours option').each(function() {
this.selected = ( this.text.toLowerCase() === color.toLowerCase() );
});
}
setColor('BLUE');
It does a case-insensitive match. If you want case sensitivity, then remove both .toLowerCase()
calls.
Or here's an alternate version of the same thing:
function setColor( color ) {
$('#drpColours option').attr('selected', function() {
return ( this.text.toLowerCase() === color.toLowerCase() );
});
}
setColor('BLUE');
精彩评论