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

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

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

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

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


当前回答

我在上面的例子中遇到了一个问题,这个问题是由于我的选择框值预填充了6个字符的固定长度字符串,但传入的参数不是固定长度。

我有一个rpad函数,它将右垫字符串,到指定的长度,并与指定的字符。因此,填充参数后,它可以工作。

$('#wsWorkCenter').val(rpad(wsWorkCenter, 6, ' '));


function rpad(pStr, pLen, pPadStr) {
if (pPadStr == '') {pPadStr == ' '};
while (pStr.length < pLen)
    pStr = pStr + pPadStr;
return pStr; 
} 

其他回答

为了避免所有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;
}

我还没有测试过,但这可能对你有用。

$("select#my-select option")
   .each(function() { this.selected = (this.text == myVal); });

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

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

为我工作。

看看jquery selectedbox插件

selectOptions(value[, clear]): 

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

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

 $('#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');
});