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

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

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

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

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


当前回答

为了避免所有jQuery版本的复杂性,我真诚地建议使用这些非常简单的javascript函数之一…

function setSelectByValue(eID,val)
{ //Loop through sequentially//
  var ele=document.getElementById(eID);
  for(var ii=0; ii<ele.length; ii++)
    if(ele.options[ii].value==val) { //Found!
      ele.options[ii].selected=true;
      return true;
    }
  return false;
}

function setSelectByText(eID,text)
{ //Loop through sequentially//
  var ele=document.getElementById(eID);
  for(var ii=0; ii<ele.length; ii++)
    if(ele.options[ii].text==text) { //Found!
      ele.options[ii].selected=true;
      return true;
    }
  return false;
}

其他回答

非常精细,其他的似乎都不管用

选择美元(“[name = " dropdown’美元)。(儿童)短信先生(“”)。道具(selected, true);

为我工作。

我发现通过使用attr,你最终会选择多个选项,当你不想-解决方案是使用prop:

$(“#myDropDown option:text=“+ myText +”)。道具(selected”、“selected”);

这里有一个简单的选择。只需设置列表选项,然后将其文本设置为选定值:

$("#ddlScheduleFrequency option").selected(text("Select One..."));

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> 选择< - >

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

      var textToSelect = "Hello World";

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

希望它能帮助到别人。