tags:

views:

29

answers:

1

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 value. 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.

+3  A: 

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');
patrick dw
Just for fun: this jsPerf test (http://jsperf.com/set-selected-option-based-on-contents) shows that the first version is faster.
Dan Manastireanu
@Dan - Thanks for the test. :o) It doesn't surprise me too much. A while back I was looking at what jQuery does when you pass a function to some of these methods that can accept one, and as I remember, there was a bit of extra work involved.
patrick dw