So, I am writing an application that requires an address, and I have a select element for the user to select a state / province. It must support the US and Canada so that it optgroups to separate them and one first level parameter as the default value. Here is an 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> <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> </optgroup>
Now I need to programmatically select the parameter corresponding to the input signal of an external source, and I want to check the correspondence based on both the value of the option element and its text. No matter which option is a match, it will be selected as the selected parameter. I know that you can set the selected option by value using
$("#state").val(myValue)
and I know that you can set the option based on text 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 check if it is an optgroup, and then runs through all its children to check for consistency? Is there a simple way through jQuery to combine the values โโand text methods of setting the selected parameter?
Another complication I'm going to do is in an external jQuery plugin. Inside the function I need to change. I have a select element as a variable
$element
so I need to do this somehow, if possible:
$element.descendents(":option").filter(function() {
source share