Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting a select by label via jquery in 1.4

Tags:

jquery

In jquery 1.3.2, the following works:

<select id="c">
  <option value="325">Red</option>
  <option value="833">Purple</option>
</select>

$('#c').val('Red');

And it changes the select to the option with RED as its label. In jQuery 1.4 this fails. How can I get the same result in 1.4? Was this a bug in the 1.3 version?

like image 736
Stomped Avatar asked Feb 24 '10 07:02

Stomped


2 Answers

You would have to do it this way:

$('option:contains("Red")', '#c')[0].selected = true

EDIT

@Tomalak

If the labels arent mutually exclusivey you'd need to rewrite the selector:

$.fn.labselect = function(str) {
    $('option', this).filter(function() {
       return $(this).text() == str;
    })[0].selected = true;

    return this;
};

// Use it like this
$('#c').labselect('Red');
like image 156
aefxx Avatar answered Oct 15 '22 23:10

aefxx


$('#c').val('Red');

shouldn't have (imho) worked in jQuery 1.3 because "Red" isn't the value. "325" is. What does this do:

$('#c').val("325");
like image 28
cletus Avatar answered Oct 15 '22 23:10

cletus