[英]Selecting options in a select via JQuery
I have a select with the following options: 我有一个选择,有以下选项:
<select>
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
</select>
I don't know what the values are, but in my JQuery code, I want to select option two because I know that the text is B (but nothing else). 我不知道这些值是什么,但在我的JQuery代码中,我想选择第二个选项,因为我知道文本是B(但没有别的)。
How can it be done? 如何做呢?
You can use the :contains()
selector: 您可以使用
:contains()
选择器:
$('option:contains("B")').prop('selected', true);
Alternatively: 或者:
$('option')
.filter(function() {
return this.text == 'B';
})
.prop('selected', true);
If you're not sure what the values are, but know what the text inside is, you can use the :contains()
selector to get the appropriate option, get its value, then set the select. 如果您不确定值是什么,但知道里面的文本是什么,您可以使用
:contains()
选择器来获取适当的选项,获取其值, 然后设置选择。
Note that :contains()
performs a substring match, so :contains(foo)
will select both <p>foo</p>
and <p>barfoobar</p>
(as ThiefMaster points out in the comments ). 注意
:contains()
执行子串匹配,因此:contains(foo)
将同时选择<p>foo</p>
和<p>barfoobar</p>
(正如ThiefMaster 在评论中指出的那样)。
For more granular control on selection, you'll want the .filter()
option I've mentioned farther down. 为了更精细地控制选择,你需要我提到的
.filter()
选项更进一步。
// relevant option
// : not entirely sure if .val() will get an option's value
var _optionval = $('option:contains("B")').attr('value');
// set select value
$('select').val(_optionval);
I'm sharing the following based off of your comment on Jack's answer. 我根据你对杰克答案的评论分享以下内容。
:contains()
is basically designed to perform a matching against an element's contents. :contains()
基本上是为了对元素的内容进行匹配。 No going around that. 没有绕过那个。
You can, however, use something like .filter()
to write more complicated code. 但是,您可以使用
.filter()
类的东西来编写更复杂的代码。
$('option').filter(function () {
// we want the option (or optionS) with text that starts with "foo"
return $(this).text().indexOf('foo') === 0;
// or maybe just something with an exact match
//
// return $(this).text() === 'foo';
});
<select id="select_id">
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
</select>
$("#select_id option").each(function (){
if($(this).text()=='B'){
// DO what you want to
}
});
this code will select your any option in select field with text "B". 此代码将在选择字段中选择带有文本“B”的任何选项。 i think this is what you want
我想这就是你想要的
试试这个(确保你选择一个ID,我使用mySelect
):
$("#mySelect").val($("#mySelect:option:contains('B')").val());
$('option').each(function(){
var t=this
if(t.text=='B'){
t.selected='selected';
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.