Reputation: 25701
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).
How can it be done?
Upvotes: 3
Views: 1395
Reputation: 41
$('option').each(function(){
var t=this
if(t.text=='B'){
t.selected='selected';
}
});
Upvotes: 1
Reputation: 14747
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.
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).
For more granular control on selection, you'll want the .filter()
option I've mentioned farther down.
// 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. No going around that.
You can, however, use something like .filter()
to write more complicated code.
$('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';
});
Upvotes: 3
Reputation: 802
<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". i think this is what you want
Upvotes: 2
Reputation: 173522
You can use the :contains()
selector:
$('option:contains("B")').prop('selected', true);
Alternatively:
$('option')
.filter(function() {
return this.text == 'B';
})
.prop('selected', true);
Upvotes: 4
Reputation: 56429
Try this (make sure you give your select an ID, i've used mySelect
):
$("#mySelect").val($("#mySelect:option:contains('B')").val());
Upvotes: 1