我有以下HTML
<SELECT id='cars'>
<OPTION value='1'>Car One</option>
<OPTION value='2'>Second Car</option>
<OPTION value='3'>Another Car</option>
</SELECT>
我知道我可以使用将下拉控件的选定值更改为任何值
$('#cars').val(2); // This will make the combo text: Second Car
但是,如何使用文本而不是值来选择值呢?
我需要做的是:
$('#cars').val('Another Car');
或
$('#cars').text('Another Car');
但那没有效果。。。
有什么帮助吗?
如果您想获得包含文本的值,那么您可以使用contains:
$('#cars option:contains("Another Car")');
根据@Burimi的建议:contains也会尝试匹配它的值,所以你必须使用文本属性
$('#cars').find('option[text*="Another Car"]').val();
很抱歉,对评论造成的混淆。但包含的只是匹配它的文本,而不是它的值。
试试这个
var text="text";
var check=$('#cars').find('option[text='+text'+]').val();
$('#cars').val(check);