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 the text description I have (as opposed to the value, which I don't have).
I know setting it by value is pretty trivial. e.g.
$("#my-select").val(myVal);
But I'm a bit stumped on doing it via the text description. I guess there must be a way of getting the value out from the text description, but my brain is too Friday afternoon-ed to be able to work it out.
We can select text or we can also find the position of a text in a drop down list using option:selected attribute or by using val() method in jQuery. By using val() method : The val() method is an inbuilt method in jQuery which is used to return or set the value of attributes for the selected elements.
You can select on any attribute and its value by using the attribute selector [attributename=optionalvalue] , so in your case you can select the option and set the selected attribute. $("div. id_100 > select > option[value=" + value + "]"). prop("selected",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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With