I have been using the following code (with jQuery v1.4.2) to set the \'selected\' attribute of a select list based on its \'text\' description rather than its \'value\':
try this:
$("#mySelect1").find("option[text=" + text1 + "]").attr("selected", true);
In case someone google for this, the solutions above didn't work for me so i ended using "pure" javascript
document.getElementById("The id of the element").value = "The value"
And that would set the value and make the current value selected in the combo box. Tested in firefox.
it was easier than keep googling a solution for jQuery
I tried a few of these things until I got one to work in both Firefox and IE. This is what I came up with.
$("#my-Select").val($("#my-Select" + " option").filter(function() { return this.text == myText }).val());
another way of writing it in a more readable fasion:
var valofText = $("#my-Select" + " option").filter(function() {
return this.text == myText
}).val();
$(ElementID).val(valofText);
Pseudocode:
$("#my-Select").val( getValOfText( myText ) );
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.
I usually use:
$("#my-Select option[text='" + myText +"']").attr("selected","selected") ;
If you want to selected value on drop-down text bases so you should use below changes: Here below is example and country name is dynamic:
<select id="selectcountry">
<option value="1">India</option>
<option value="2">Ireland</option>
</select>
<script>
var country_name ='India'
$('#selectcountry').find('option:contains("' + country_name + '")').attr('selected', 'selected');
</script>