开发者

set item in select list to be selected

开发者 https://www.devze.com 2023-01-21 03:39 出处:网络
I have a select list like so: <select id=\"drpColours\"> <option value=\"\" selected=\"selected\">Choose color</option>

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');
0

精彩评论

暂无评论...
验证码 换一张
取 消