How would I select my dropdown list item by text rather than value?
I want to select a dropdown item by text with jQuery.
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.
Here's the code I use (it's not quite the same as the other suggestions here, and works with jQuery v1.8.3)
var userToSearchFor = 'mike'; // Select any options containing this text
$("#ListOfUsers").find("option:contains('" + userToSearchFor +"')").each(function () {
$(this).attr("selected", "selected");
});
<select id="ListOfUsers" ></select>
Hope this helps.
I had a similar scenario with dropdowns for country, state and city. Country had "India" as well as "British Indian Ocean Territory". The issue with :contains() is that it attempts on both matches. I did something like:
$('#country option').each(function(){
if($(this).text() == 'India'){
$(this).prop('selected', true).trigger('change');
}
});