title: jQuery - Set the selected option of a select box using value or text with options nested in optgroups
body: <p>So I am writing an app that requires an address input and I have a <code>select</code> element for the user to select the state/province. It needs to support the <code>US</code> and <code>Canada</code> so it has nested <code>optgroups</code> to separate those out and a single, first level option as it's default value. Here is a basic example:</p>
  
  <pre><code>&lt;select name="state" id="state"&gt;
    &lt;option class="co" value="" data-placeholder="true" disabled selected&gt;Choose your state...&lt;/option&gt;
    &lt;optgroup label="United States"&gt;
      &lt;option class="co" value="AL"&gt;Alabama&lt;/option&gt;
      &lt;option class="co" value="AK"&gt;Alaska&lt;/option&gt;
      &lt;option class="co" value="AZ"&gt;Arizona&lt;/option&gt;
    &lt;/optgroup&gt;
    &lt;optgroup label="Canada"&gt;
      &lt;option class="co" value="AB"&gt;Alberta&lt;/option&gt;
      &lt;option class="co" value="BC"&gt;British Columbia&lt;/option&gt;
      &lt;option class="co" value="MB"&gt;Manitoba&lt;/option&gt;
    &lt;/optgroup&gt;
  </code></pre>
  
  <p></p>
  
  <p>Now I need to programmatically select the option that matches input from an external source and I want to check for a match based on both the value of the option element or its text. Whichever option is a match would then be set as the selected option. I know you can set the selected option by value using</p>
  
  <pre><code>$("#state").val(myValue)
  </code></pre>
  
  <p>and I know you can set an option based on text in this way</p>
  
  <pre><code>var myText = "The state I want.";
  $("#state").children().filter(function() {
    return $(this).text() == myText;
  }).prop('selected', true);
  </code></pre>
  
  <p>Is there a clean way to do this without having to run through each child and checking if it's an optgroup and then running through all its children to check for a match? Is there an easy way through jQuery to combine the value and text methods of setting the selected option?</p>
  
  <p>One other complication, I am going to be doing this within an external jQuery plugin. Within the function I need to modify I have the select element as a variable</p>
  
  <pre><code>$element
  </code></pre>
  
  <p>so I need a way to do it kind of like this if possible:</p>
  
  <pre><code>$element.descendents(":option").filter(function() {
    //do the selecting here
  }).prop('selected', true);
  </code></pre>