If your <option>
elements don't have value
attributes, then you can just use .val
:
$selectElement.val("text_you're_looking_for")
However, if your <option>
elements have value attributes, or might do in future, then this won't work, because whenever possible .val
will select an option by its value
attribute instead of by its text content. There's no built-in jQuery method that will select an option by its text content if the options have value
attributes, so we'll have to add one ourselves with a simple plugin:
/*
Source: https://stackoverflow.com/a/16887276/1709587
Usage instructions:
Call
jQuery('#mySelectElement').selectOptionWithText('target_text');
to select the <option> element from within #mySelectElement whose text content
is 'target_text' (or do nothing if no such <option> element exists).
*/
jQuery.fn.selectOptionWithText = function selectOptionWithText(targetText) {
return this.each(function () {
var $selectElement, $options, $targetOption;
$selectElement = jQuery(this);
$options = $selectElement.find('option');
$targetOption = $options.filter(
function () {return jQuery(this).text() == targetText}
);
// We use `.prop` if it's available (which it should be for any jQuery
// versions above and including 1.6), and fall back on `.attr` (which
// was used for changing DOM properties in pre-1.6) otherwise.
if ($targetOption.prop) {
$targetOption.prop('selected', true);
}
else {
$targetOption.attr('selected', 'true');
}
});
}
Just include this plugin somewhere after you add jQuery onto the page, and then do
jQuery('#someSelectElement').selectOptionWithText('Some Target Text');
to select options.
The plugin method uses filter
to pick out only the option
matching the targetText, and selects it using either .attr
or .prop
, depending upon jQuery version (see .prop() vs .attr() for explanation).
Here's a JSFiddle you can use to play with all three answers given to this question, which demonstrates that this one is the only one to reliably work: http://jsfiddle.net/3cLm5/1/