我有一个选择控件,在一个javascript变量,我有一个文本字符串。
使用jQuery,我想设置选择控件的选定元素为我有文本描述的项目(而不是值,这是我没有的)。
我知道用值来设置它很简单。如。
$("#my-select").val(myVal);
但我有点难住了,通过文本描述。我想一定有办法从文本描述中得到价值,但我的大脑在周五下午太忙了,无法解决这个问题。
我有一个选择控件,在一个javascript变量,我有一个文本字符串。
使用jQuery,我想设置选择控件的选定元素为我有文本描述的项目(而不是值,这是我没有的)。
我知道用值来设置它很简单。如。
$("#my-select").val(myVal);
但我有点难住了,通过文本描述。我想一定有办法从文本描述中得到价值,但我的大脑在周五下午太忙了,无法解决这个问题。
当前回答
$("#Test").find("option:contains('two')").each(function(){
if( $(this).text() == 'two' ) {
$(this).attr("selected","selected");
}
});
if语句与"two"进行精确匹配,"two 3 "将不会被匹配
其他回答
这句话很管用:
$("#myDropDown option:contains(myText)").attr('selected', true);
$("#Test").find("option:contains('two')").each(function(){
if( $(this).text() == 'two' ) {
$(this).attr("selected","selected");
}
});
if语句与"two"进行精确匹配,"two 3 "将不会被匹配
这里有一个很简单的方法。请使用它
$("#free").val("y").change();
$('#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');
});
我还没有测试过,但这可能对你有用。
$("select#my-select option")
.each(function() { this.selected = (this.text == myVal); });