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
Get the children of the select box; loop through them; when you have found the one you want, set it as the selected option; return false to stop looping.
take a look at the jquery selectedbox plugin
selectOptions(value[, clear]):
Select options by value, using a string as the parameter $("#myselect2").selectOptions("Value 1");
, or a regular expression $("#myselect2").selectOptions(/^val/i);
.
You can also clear already selected options: $("#myselect2").selectOptions("Value 2", true);
var text1 = 'Two';
$("select option").filter(function() {
//may want to use $.trim in here
return $(this).text() == text1;
}).prop('selected', true);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select>
<option value="0">One</option>
<option value="1">Two</option>
</select>
var text1 = 'Two';
$("select option").filter(function() {
//may want to use $.trim in here
return $(this).text() == text1;
}).attr('selected', true);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.4.0/jquery.min.js"></script>
<select>
<option value="0">One</option>
<option value="1">Two</option>
</select>
Note that while this approach will work in versions that are above 1.6 but less than 1.9, it has been deprecated since 1.6. It will not work in jQuery 1.9+.
val()
should handle both cases.
$('select').val('1'); // selects "Two"
$('select').val('Two'); // also selects "Two"
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<select>
<option value="0">One</option>
<option value="1">Two</option>
</select>
Just on a side note. My selected value was not being set. And i had search all over the net. Actually i had to select a value after a call back from a web service, because i was getting data from it.
$("#SelectMonth option[value=" + DataFromWebService + "]").attr('selected', 'selected');
$("#SelectMonth").selectmenu('refresh', true);
So the refresh of the selector was was the only thing that i was missing.