jQuery: Setting select list 'selected' based on text, failing strangely
Solution 1:
When an <option>
isn't given a value=""
, the text becomes its value
, so you can just use .val()
on the <select>
to set by value, like this:
var text1 = 'Monkey';
$("#mySelect1").val(text1);
var text2 = 'Mushroom pie';
$("#mySelect2").val(text2);
You can test it out here, if the example is not what you're after and they actually have a value, use the <option>
element's .text
property to .filter()
, like this:
var text1 = 'Monkey';
$("#mySelect1 option").filter(function() {
return this.text == text1;
}).attr('selected', true);
var text2 = 'Mushroom pie';
$("#mySelect2 option").filter(function() {
return this.text == text2;
}).attr('selected', true);
You can test that version here.
Solution 2:
$("#my-select option:contains(" + myText +")").attr("selected", true);
This returns the first option containing your text description.
Solution 3:
try this:
$("#mySelect1").find("option[text=" + text1 + "]").attr("selected", true);
Solution 4:
Using the filter() function seems to work in your test cases (tested in Firefox). The selector would look like this:
$('#mySelect1 option').filter(function () {
return $(this).text() === 'Banana';
});