Skip to content

Instantly share code, notes, and snippets.

Last active Jan 16, 2019
What would you like to do?
Just the javascript from the state/city selector example
// 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
// 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
// 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
// if the child's value is in a visible optgroup, select it
if ( child_select.find('option[value="' + child_value + '"]').is(':visible')) {
// now that everyting is defined, set our initial condition by triggering a state change in the parent selector
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment