Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 select element for the user to select the state/province. It needs to support the US and Canada so it has nested optgroups 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>
  <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 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

$("#state").val(myValue)

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

$element

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);
like image 343
climbak Avatar asked Nov 27 '22 21:11

climbak


1 Answers

If you want to select by the option value, use the value selector:

var myText = "AZ";
$('#state option[value="' + myText + '"]').prop('selected', true);

If you want to search by the option's label, use a filter:

var myText = "Arizona";
$('#state option').filter(function () { return $(this).html() == myText; }).prop('selected', true)
like image 119
asgallant Avatar answered Dec 09 '22 18:12

asgallant