How do I select an item by its text value in a dropdown using jQuery?

前端 未结 4 617
野趣味
野趣味 2020-12-31 07:35

If I had the following select, and did not know the value to use to select an item in advance like in this question or the index of the item I wanted selected, how could I s

相关标签:
4条回答
  • 2020-12-31 07:53
    $("#list option").each(function() {
      this.selected = $(this).text() == "Option C";
    });
    
    0 讨论(0)
  • 2020-12-31 07:55
    var option;
    $('#list option').each(function() {
        if($(this).text() == 'Option C') {
            option = this;
            return false;
        }
    });
    
    0 讨论(0)
  • 2020-12-31 08:03

    This should do the trick:

    // option text to search for
    var optText = "Option B";
    // find option value that corresponds
    var optVal = $("#list option:contains('"+optText+"')").attr('value');
    // select the option value 
    $("#list").val( optVal )
    

    As eyelidlessness points out, this will behave unpredictably when the text being searched for can be found in more than one option.

    0 讨论(0)
  • 2020-12-31 08:08
    function SelectItemInDropDownList(itemToFind){    
             var option;
             $('#list option').each(function(){
                 if($(this).text() == itemToFind) {
                     option = this;
                     option.selected = true;
                     return false;    
                    }
               });  }
    

    I only modified the previous code because it only located the option in the select list, some may want a literal demonstration.

    0 讨论(0)
提交回复
热议问题