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

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

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

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

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


当前回答

1.7+最简单的方法是:

$("#myDropDown option:text=" + myText +"").attr("selected", "selected"); 

1.9+

$("#myDropDown option:text=" + myText +"").prop("selected", "selected"); 

测试和工作。

其他回答

这句话很管用:

$("#myDropDown option:contains(myText)").attr('selected', true);

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

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

为了避免所有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;
}
 $('#theYear').on('change', function () {
 FY = $(this).find('option:selected').text();
 $('#theFolders').each(function () {
     $('option:not(:contains(' + FY + '))', this).hide();
 });
 $('#theFolders').val(0);
});

$('#theYear').on('mousedown', function () {
 $('#theFolders option').show().find('option:contains("Select")', this).attr('selected', 'selected');
});

获取选择框的子元素;循环遍历它们;当你找到你想要的选项时,将其设置为所选选项;返回false停止循环。