Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If your <code>&lt;option&gt;</code> elements don't have <code>value</code> attributes, then you can just use <a href="http://api.jquery.com/val/#val2" rel="nofollow noreferrer"><code>.val</code></a>:</p> <pre><code>$selectElement.val("text_you're_looking_for") </code></pre> <p>However, if your <code>&lt;option&gt;</code> elements have value attributes, or might do in future, then this won't work, because whenever possible <code>.val</code> will select an option by its <code>value</code> 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 <code>value</code> attributes, so we'll have to add one ourselves with a simple plugin:</p> <pre><code>/* Source: https://stackoverflow.com/a/16887276/1709587 Usage instructions: Call jQuery('#mySelectElement').selectOptionWithText('target_text'); to select the &lt;option&gt; element from within #mySelectElement whose text content is 'target_text' (or do nothing if no such &lt;option&gt; 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'); } }); } </code></pre> <p>Just include this plugin somewhere after you add jQuery onto the page, and then do</p> <pre><code>jQuery('#someSelectElement').selectOptionWithText('Some Target Text'); </code></pre> <p>to select options.</p> <p>The plugin method uses <a href="http://api.jquery.com/filter/" rel="nofollow noreferrer"><code>filter</code></a> to pick out only the <code>option</code> matching the targetText, and selects it using either <code>.attr</code> or <code>.prop</code>, depending upon jQuery version (see <a href="https://stackoverflow.com/questions/5874652/prop-vs-attr">.prop() vs .attr()</a> for explanation).</p> <p>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: <a href="http://jsfiddle.net/3cLm5/1/" rel="nofollow noreferrer">http://jsfiddle.net/3cLm5/1/</a></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload