jQuery Chaining Country / State Selects with OptGroup
I have the following 2 select lists.. I'd like to hide State/Prov until the chosen Country has a corresponding optgroup label. So..
--User Selects Alegeria.. No State select is shown..
--User Selects United States or Canada; The State Selects appears showing only the values where optgroup label matches the parents name.
Make Sense? Can't find a way to do it based on OptGroup vs. having to manually assign a 'class' to each child object
<select id="C_Country" name="C_Country" aria-required="true" class="required">
<option value=" " selected="">-- Please Select --</option>
<option value="AF">Afghanistan</option>
<option value="AX">Aland Islands</option>
<option value="USA">United States</option>
<option value="DZ">Algeria</option>
<option value="CA">Canada</option>
<option value="AD">Andorra</option>
</select>
<p><label for="C_State_Prov">State or Province <span title="required">*</span></label></p>
<select id="C_State_Prov" name="C_State_Prov" aria-required="true" class="required">
<option value="" selected="">-- Please Select --</option>
<optgroup label="United St开发者_运维知识库ates">
<option value="AK">Alaska</option>
<option value="AL">Alabama</option>
<option value="AR">Arkansas</option>
<option value="AZ">Arizona</option>
<option value="CA">California</option>
</optgroup>
<optgroup label="Canada">
<option value="AB">Alberta</option>
<option value="BC">British Columbia</option>
<option value="MB">Manitoba</option>
</optgroup>
</select>
I think this is what you want.
$(function(){
var state_province = $('#C_State_Prov option, #C_State_Prov optgroup');
state_province.hide(); // hide all state and provinces on page load
$('#C_Country').change(function(){
state_province.hide(); // on change of drop down hide all state provinces
// find the optgroup with the label = the html of the selected dropdown
// select the opt group and all of it's children and show them
$("#C_State_Prov optgroup[label='"+$(this).find(':selected').html() + "']")
.children()
.andSelf()
.show();
});
});
This can be cleaned up a little more but you get the idea.
精彩评论