Skip to content

Instantly share code, notes, and snippets.

@xnau
Last active Jan 16, 2019
Embed
What would you like to do?
Just the javascript from the state/city selector example
<script>
jQuery(function($){
// name of the parent field
var parent = 'state';
// name of the child field
var child = 'city';
// defines the parent selector dropdown
var parent_select = $('select[name='+parent+']');
// defines the child selector dropdown
var child_select = $('select[name='+child+']');
// holds the initial child value
var child_value = '';
// a reset function to clear the child selector and hide all the optgroups
var clear_child = function () {
// save the current child value
child_value = child_select.val();
// clear the child control
child_select.val('').find('optgroup').css('display','none');
}
// this is where we attach our handler to the parent selector
// the handler gets called when the parent selector's value is chosen,
// which generates a "change" event...the handler is attached to that event
parent_select.on( 'change', function() {
// hide any child options that were made visible before
clear_child();
// identify the group that was selected
var selection = $(this).find('option:selected').text();
// find the corresponding optgroup in the child selector
var child_group = child_select.find('optgroup[label*="'+selection+'"]');
// make that one optgroup visible
child_group.css('display','inherit');
// if the child's value is in a visible optgroup, select it
if ( child_select.find('option[value="' + child_value + '"]').is(':visible')) {
child_select.val(child_value);
}
});
// now that everyting is defined, set our initial condition by triggering a state change in the parent selector
parent_select.trigger('change');
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment