I have a select control, and in a javascript variable I have a text string.
Using jQuery I want to set the selected element of the select control to be the item with
$("#myselect option:contains('YourTextHere')").val();
will return the value of the first option containing your text description. Tested this and works.
$("#Test").find("option:contains('two')").each(function(){
if( $(this).text() == 'two' ) {
$(this).attr("selected","selected");
}
});
The if statement does a exact match with "two" and "two three" will not be matched
Very fiddly and nothing else seemed to work
$('select[name$="dropdown"]').children().text("Mr").prop("selected", true);
worked for me.
To avoid all jQuery version complications, I honestly recommend using one of these really simple javascript functions...
function setSelectByValue(eID,val)
{ //Loop through sequentially//
var ele=document.getElementById(eID);
for(var ii=0; ii<ele.length; ii++)
if(ele.options[ii].value==val) { //Found!
ele.options[ii].selected=true;
return true;
}
return false;
}
function setSelectByText(eID,text)
{ //Loop through sequentially//
var ele=document.getElementById(eID);
for(var ii=0; ii<ele.length; ii++)
if(ele.options[ii].text==text) { //Found!
ele.options[ii].selected=true;
return true;
}
return false;
}
This accepted answer does not seem correct, while .val('newValue') is correct for the function, trying to retrieve a select by its name does not work for me, I had to use the id and classname to get my element
If you are trying to bind select with ID then the following code worked for me.
<select name="0product_id[]" class="groupSelect" id="groupsel_0" onchange="productbuilder.update(this.value,0);">
<option value="0" class="notag" id="id0_0">--Select--</option>
<option class="notag" value="338" id="id0_338" >Dual Promoter Puromycin Expression Plasmid - pSF-CMV-PGK-Puro > £114.00</option>
<option class="notag" value="282" id="id0_282" >EMCV IRES Puromycin Expression Plasmid - pSF-CMV-EMCV-Puro > £114.00</option>
<option class="notag" value="265" id="id0_265" >FMDV IRES Puromycin Expression Plasmid - pSF-CMV-FMDV-Puro > £114.00</option>
<option class="notag" value="101" id="id0_101" >Puromycin Selection Plasmid - pSF-CMV-Ub-Puro AscI > £114.00</option>
<option class="notag" value="105" id="id0_105" >Puromycin Selection SV40 Ori Plasmid - pSF-CMV-Ub-Puro-SV40 Ori SbfI > £114.00</option></select>
AND THIS IS TEH JS CODE
$( document ).ready(function() {
var text = "EMCV IRES Puromycin Expression Plasmid - pSF-CMV-EMCV-Puro > £114.00";
alert(text);
$("#groupsel_0 option").filter(function() {
//may want to use $.trim in here
return $(this).text() == text;
}).prop('selected', true);
});