Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
55
rated 0 times [  57] [ 2]  / answers: 1 / hits: 96249  / 11 Years ago, thu, july 25, 2013, 12:00:00

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);

More From » jquery

 Answers
3

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
$element.find(option).filter(function(){
return ( ($(this).val() == value) || ($(this).text() == value) )
}).prop('selected', true);
}

[#76739] Wednesday, July 24, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
americar

Total Points: 631
Total Questions: 107
Total Answers: 103

Location: Luxembourg
Member since Tue, Jan 25, 2022
2 Years ago
;