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

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

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

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

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


当前回答

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

其他回答

看看jquery selectedbox插件

selectOptions(value[, clear]): 

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

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

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

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

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


function rpad(pStr, pLen, pPadStr) {
if (pPadStr == '') {pPadStr == ' '};
while (pStr.length < pLen)
    pStr = pStr + pPadStr;
return pStr; 
} 
 $('#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');
});

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

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

希望它能帮助到别人。