jQuery: Setting select list 'selected' based on text, failing strangely
$("#my-select option:contains(" + myText +")").attr("selected", true);
This returns the first option containing your text description.
try this:
$("#mySelect1").find("option[text=" + text1 + "]").attr("selected", true);
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.