jQuery - How to select dropdown list item by text?

2019-03-23 23:04发布

问题:

How would I select my dropdown list item by text rather than value?

I want to select a dropdown item by text with jQuery.

回答1:

use :contains()(link)

$("select option:contains(text)").attr('selected', true);

demo



回答2:

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.



回答3:

i think this will do the trick for you...

$("#selectId").find("option:contains('text')").each(function(){
  if( $(this).text() == 'Text that should be matched' ) {
    $(this).attr("selected","selected");
  }
});


回答4:

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.



回答5:

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');
    }
});


回答6:

$("selecter option:contains('" + data[i].ID+ "')").attr('selected', 'selected');