I have a select "usercountry" that has a predefined option selected when the page loads. I have a second select organized with optgroup country and child option state. I have a jQuery script that will change/show the optgroup and child option states accordingly when the usercountry is chosen. The problem is when the page loads with "United States" preselected I need the optgroup United States preloaded.
HTML:
<select name="usercountry" id="usercountry" class="required">
<option value="">-- Please Choose --</option>
<option value="13">Australia</option>
<option value="38">Canada</option>
<option value="223" selected>United States</option>
<option value="239">Zimbabwe</option>
</select>
<select name="userstate" id="userstate" class="required">
<option value="" selected>Please Choose..</option>
<optgroup label="Australia">
<option value="New South Wales">New South Wales</option>
<option value="Northern Territory">Northern Territory</option>
<option value="Queensland">Queensland</option>
</optgroup>
<optgroup label="Canada">
<option value="Alberta">Alberta</option>
<option value="British Columbia">British Columbia</option>
<option value="Manitoba">Manitoba</option>
<option value="New Brunswick">New Brunswick</option>
</optgroup>
<optgroup label="United States">
<option value="Alabama">Alabama</option>
<option value="Alaska">Alaska</option>
<option value="Arizona">Arizona</option>
<option value="Arkansas">Arkansas</option>
<option value="California">California</option>
<option value="Colorado">Colorado</option>
<option value="Connecticut">Connecticut</option>
</optgroup>
<optgroup label="Zimbabwe">
<option value="Bulawayo">Bulawayo</option>
<option value="Harare">Harare</option>
<option value="Manicaland">Manicaland</option>
<option value="Midlands">Midlands</option>
</optgroup>
</select>
jQuery:
// sets the option group using the same code you already use for on-country-change
function setOptGroup() {
var state_province = $('#userstate option, #userstate optgroup');
state_province.hide();
// EDIT: this line won't retrieve selected country when page has just been loaded
//$("#userstate optgroup[label='" + $(this).find(':selected').html() + "']")
// this line works
$("#userstate optgroup[label='" + $('#usercountry option:selected').text() + "']")
.children()
.andSelf()
.show();
}
$( document ).ready(function() {
// set up the USA option group when the page is loaded
setOptGroup();
// your present code - refactored a bit
$('#usercountry').change(setOptGroup); // edit to fix typo
});
Any help is greatly appreciated!
EDIT: Here is the jsFiddle of Annabel's suggestion http://jsfiddle.net/goodegg/phj8q/ EDIT: The Code above works thanks to Annabel, see the ejsFiddle above for the final version