我有一个选择控件,在一个javascript变量,我有一个文本字符串。

使用jQuery,我想设置选择控件的选定元素为我有文本描述的项目(而不是值,这是我没有的)。

我知道用值来设置它很简单。如。

$("#my-select").val(myVal);

但我有点难住了,通过文本描述。我想一定有办法从文本描述中得到价值,但我的大脑在周五下午太忙了,无法解决这个问题。


当前回答

Try

[...mySelect.options].forEach(o=> o.selected = o.text == 'Text C' )

[... mySelect选项)。前言(o=> o.选择= o.文本=“文本C”); 选择< id =“mySelect > <option value=“A”>短信A</option> <option value=“B”>短信B</option> <option value=“C”>短信</option> 选择< - >

其他回答

 $("#Test").find("option:contains('two')").each(function(){
     if( $(this).text() == 'two' ) {
        $(this).attr("selected","selected");
     }
 });

if语句与"two"进行精确匹配,"two 3 "将不会被匹配

看看jquery selectedbox插件

selectOptions(value[, clear]): 

按值选择选项,使用字符串作为参数$("#myselect2")。selectOptions("Value 1");,或者正则表达式$("#myselect2").selectOptions(/^val/i);。

你也可以清除已经选择的选项:$("#myselect2")。selectOptions("Value 2", true);

试试这个…选择myText文本选项

$("#my-Select option[text=" + myText +"]").prop("selected", true);

这里有一个很简单的方法。请使用它

$("#free").val("y").change();

我知道这是一篇老文章,但是我无法使用jQuery 1.10.3和上面的解决方案来实现文本选择。 我最终使用以下代码(spoulson的解决方案的变化):

      var textToSelect = "Hello World";

      $("#myDropDown option").each(function (a, b) {
            if ($(this).html() == textToSelect ) $(this).attr("selected", "selected");
        });

希望它能帮助到别人。