我需要检查<select>是否有一个文本等于特定值的选项。

例如,如果有一个<option value="123">abc</option>,我将寻找"abc"。

有选择器来做这个吗?

我在寻找类似于$('#选择选项[值="123"]');除了文本。


当前回答

2022年8月25日。

对于jQuery v3.5.1,真正对我有用的是:

$('#selectID option:contains("label")').prop('selected', true);

如果你在一个变量中有文本,这样做:

  ddText = 'Text to find';
  $('#selectID option:contains("' + ddText + '")').prop('selected', true);

其他回答

这对我很有用

var options = $(dropdown).find('option');
var targetOption = $(options).filter(
function () { return $(this).html() == value; });

console.log($(targetOption).val());

谢谢你的帖子。

这是在下拉列表中选择文本的最佳方法。

$("#dropdownid option:contains(your selected text)").attr('selected', true);

下面的jquery 1.10.2版本适合我

  var selectedText="YourMatchText";
    $('#YourDropdownId option').map(function () {
       if ($(this).text() == selectedText) return this;
      }).attr('selected', 'selected');
    });

我遇到了同样的问题,下面是工作代码:

$("#test option").filter(function() {
    return $(this).text() =='Ford';
}).prop("selected", true);

演示:http://jsfiddle.net/YRBrp/83/

我尝试了其中的一些功能,直到我找到了一个可以同时在Firefox和IE中运行的功能。这是我想到的。

$("#my-Select").val($("#my-Select" + " option").filter(function() { return this.text == myText }).val());

另一种更容易读懂的写法:

var valofText = $("#my-Select" + " option").filter(function() {
    return this.text == myText
}).val();
$(ElementID).val(valofText);

伪代码:

$("#my-Select").val( getValOfText( myText ) );