How would I select my dropdown list item by text rather than value?
I want to select a dropdown item by text with jQuery.
Projects In JavaScript & JQuery With jQuery, it's easy to get selected text from a drop-down list. This is done using the select id. To change the selected value of a drop-down list, use the val() method.
To get the text of the selected option, we first need to find the selected option using the find() method and then use the text() method to get the option text. where selectBox is the value of the id attribute of the <select> HTML tag.
Select from option value is pretty easy and it is as below: $('select option[value="test"]'). val(); So now selecting by text, If you are using jQuery and if you have an older version than 1.9 the following will work choosing by text.
use :contains()(link)
$("select option:contains(text)").attr('selected', true);
There is a filter function on jQuery that you can use to get elements with something more specific
$("select option").filter(function() { return $(this).text() == "text_to_select"; });
This is going to return all options with the "text_to_select" in the text.
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