Jquery - On Page Load Select Optgoup And Children In Second Select By A Default Selected Option In A Parent Select
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 jQu
Solution 1:
Have you put your code in a $(document).ready()
function?
Assuming your code does what you want when the user selects a different country, this is what you want to change your code to:
// sets the option group using the same code you already use for on-country-changefunctionsetOptGroup() {
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').val() + "']")
.children()
.andSelf()
.show();
}
$( document ).ready(function() {
// set up the USA option group when the page is loadedsetOptGroup();
// your present code - refactored a bit
$('#usercountry').change(setOptGroup); // edit to fix typo
});
The document.ready function will run once - when the page has finished loading. It's normal with jQuery to put a lot of code here.
Post a Comment for "Jquery - On Page Load Select Optgoup And Children In Second Select By A Default Selected Option In A Parent Select"