如何使用jQuery在下拉列表中按文本值选择项目?

时间:2022-10-31 17:56:52

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 select one of the options with jQuery if I did know the text value like Option C?

如果我有以下选择,并且不知道用于提前选择项目的值,就像在这个问题或我想要选择的项目的索引一样,如果我知道这个,我怎么能用jQuery选择一个选项选项C之类的文本值?

<select id='list'>
<option value='45'>Option A</option>
<option value='23'>Option B</option>
<option value='17'>Option C</option>
</select>

4 个解决方案

#1


14  

var option;
$('#list option').each(function() {
    if($(this).text() == 'Option C') {
        option = this;
        return false;
    }
});

#2


14  

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.

正如眼睑指出的那样,当搜索的文本可以在多个选项中找到时,这将表现得不可预测。

#3


9  

$("#list option").each(function() {
  this.selected = $(this).text() == "Option C";
});

#4


4  

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.

我只修改了以前的代码,因为它只在选择列表中找到了选项,有些可能需要文字演示。

#1


14  

var option;
$('#list option').each(function() {
    if($(this).text() == 'Option C') {
        option = this;
        return false;
    }
});

#2


14  

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.

正如眼睑指出的那样,当搜索的文本可以在多个选项中找到时,这将表现得不可预测。

#3


9  

$("#list option").each(function() {
  this.selected = $(this).text() == "Option C";
});

#4


4  

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.

我只修改了以前的代码,因为它只在选择列表中找到了选项,有些可能需要文字演示。