title: How to select an option in select by text using jQuery
body: <p>How to set an option in select by text using jQuery? The following works</p>
  
  <pre><code>$("#selectID option:contains('optionText')").attr("selected", true);
  </code></pre>
  
  <p>Is there a simpler/shorter way?</p>
  
  <p>Example</p>
  
  <pre><code>&lt;select id="fruit"&gt;
      &lt;option value=""&gt;--select--&lt;/option&gt;
      &lt;option value="1"&gt;apple&lt;/option&gt;
      &lt;option value="2"&gt;pineapple&lt;/option&gt;
      &lt;option value="3"&gt;orange&lt;/option&gt;
  &lt;select&gt;
  &lt;br&gt;
  &lt;button&gt;apple&lt;/button&gt;
  &lt;button&gt;orange&lt;/button&gt;
  &lt;button&gt;pineapple&lt;/button&gt;
  
  $(function() {
      $("button").click(function() {
          $("#fruit option:contains('" + $(this).text() + "')").attr("selected", true);
      })
  })
  </code></pre>
  
  <p><a href="http://jsfiddle.net/c2cb9/2/" rel="nofollow">Demo</a></p>
  
  <p><strong>EDIT</strong></p>
  
  <p>The version posted above using Contains has a bug. Since the Contains would match partial strings also (e.g. apple would match pineapple), it can select incorrect options.</p>
  
  <pre><code>// Doesn't work in FF4, IE9 using jQuery 1.4.4
  $('#fruit').val('apple'); // Doesn't work in FF4, IE9 using jQuery 1.4.4
  
  // Doesn't work either in FF4, IE9 using jQuery 1.4.4
  $('#fruit option[text="apple"]').attr("selected", true);
  
  // This works
  $("#fruit").children("option[text='apple']").attr("selected", true);
  </code></pre>
  
  <p><strong>EDIT</strong> Feb 14th, 2012</p>
  
  <pre><code>// The above doesn't work in jQuery 1.7.1
  
  // Using even more verbose version [Demo][2]
  
  var buttonText = $(this).text();
  
  $("#fruit option:contains('" + buttonText + "')")
      .filter(function(i){
          return $(this).text() === buttonText;
      })
      .attr("selected", true)
  </code></pre>