If I need to preselect a dropdown option with a certain value, I can use this:
$('select option[value="123"]').attr('selected', 'selected');
but if I need to preselect an option based on the text it contains I need to do all this:
$('select option').each(function() {
var $this = $(this);
if($this.text() == 'My Text') {
$this.attr('selected', 'selected');
}
});
Is there a way to do it without looping through all the option tags like the first way but based on text instead of value?
Check out the
:contains()selector.http://api.jquery.com/contains-selector/