climbak climbak - 4 months ago 22
Javascript Question

jQuery - Set the selected option of a select box using value or text with options nested in optgroups

So I am writing an app that requires an address input and I have a

element for the user to select the state/province. It needs to support the
so it has nested
to separate those out and a single, first level option as it's default value. Here is a basic example:

<select name="state" id="state">
<option class="co" value="" data-placeholder="true" disabled selected>Choose your state...</option>
<optgroup label="United States">
<option class="co" value="AL">Alabama</option>
<option class="co" value="AK">Alaska</option>
<option class="co" value="AZ">Arizona</option>
<optgroup label="Canada">
<option class="co" value="AB">Alberta</option>
<option class="co" value="BC">British Columbia</option>
<option class="co" value="MB">Manitoba</option>

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


and I know you can set an option based on text in this way

var myText = "The state I want.";
$("#state").children().filter(function() {
return $(this).text() == myText;
}).prop('selected', true);

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?

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


so I need a way to do it kind of like this if possible:

$element.descendents(":option").filter(function() {
//do the selecting here
}).prop('selected', true);


Solved. Since I already had my element passed to a function as a jQuery variable, $element, I couldn't just use the standard selector in the form of:

$("#state option").filter(
  // filter function
).prop('selected', true);

After a lot of trying, I got this and it works:

function functionIHadToChange($element, value) {
  // other code
      return ( ($(this).val() == value) || ($(this).text() == value) )
    }).prop('selected', true);