Skip to content

Instantly share code, notes, and snippets.

@xnau
Last active January 16, 2019 03:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xnau/b9d239cbaad3aa50860e08d8026bd4fd to your computer and use it in GitHub Desktop.
Save xnau/b9d239cbaad3aa50860e08d8026bd4fd to your computer and use it in GitHub Desktop.
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