[英]jQuery - How to select dropdown list item by text?
如何按文字而不是按值选择下拉列表项?
我想用jQuery按文本选择一个下拉项。
我想这会为你做的伎俩......
$("#selectId").find("option:contains('text')").each(function(){
if( $(this).text() == 'Text that should be matched' ) {
$(this).attr("selected","selected");
}
});
这是我使用的代码(它与此处的其他建议不完全相同,并与jQuery v1.8.3一起使用)
var userToSearchFor = 'mike'; // Select any options containing this text
$("#ListOfUsers").find("option:contains('" + userToSearchFor +"')").each(function () {
$(this).attr("selected", "selected");
});
<select id="ListOfUsers" ></select>
希望这可以帮助。
我有一个类似的情况,国家,州和城市的下拉菜单。 国家有“印度”以及“英属印度洋领地”。 问题:contains()
是它尝试两个匹配。 我做了类似的事情:
$('#country option').each(function(){
if($(this).text() == 'India'){
$(this).prop('selected', true).trigger('change');
}
});
$("selecter option:contains('" + data[i].ID+ "')").attr('selected', 'selected');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.