Skip to content

Instantly share code, notes, and snippets.

@shawn-crigger
Created October 9, 2014 15:02
Show Gist options
  • Save shawn-crigger/8485622ddacaff022bca to your computer and use it in GitHub Desktop.
Save shawn-crigger/8485622ddacaff022bca to your computer and use it in GitHub Desktop.
jQuery Chained Selects Plugin
/**
* Handles chained select boxs
* @author Shawn Crigger
*/
;(function ( $, window, document, undefined ) {
// Create the defaults once
var chainSelects = "chainSelects",
self = null,
defaults = {
id : 0,
action : "get_city",
url : "/do-ajax.php",
disabled_text: "<option>wait...</option>",
target : "select#city"
};
// The actual plugin constructor
function Plugin ( element, options ) {
self = this;
self.element = element;
// jQuery has an extend method which merges the contents of two or
// more objects, storing the result in the first object. The first object
// is generally empty as we don't want to alter the default options for
// future instances of the plugin
self.settings = $.extend( {}, defaults, options );
self._defaults = defaults;
self._name = chainSelects;
self._target = self.settings.target;
self.init( self.settings );
}
// Avoid Plugin.prototype conflicts
$.extend(Plugin.prototype, {
init: function ( settings ) {
// select boxes for states -> cities
$(self.element).change(function()
{
$(self._target).attr("disabled","disabled").html( settings.disabled_text );
self.settings.id = $(this).find(":selected").val();
$.ajax(
{
type: "POST",
url: "/do-ajax.php",
data: {
id : self.settings.id,
action : self.settings.action
},
cache: false,
success: function(html)
{
$(self._target).removeAttr("disabled").html(html);
}
});
});
}
});
// A really lightweight plugin wrapper around the constructor,
// preventing against multiple instantiations
$.fn[ chainSelects ] = function ( options ) {
this.each(function() {
if ( !$.data( this, "plugin_" + chainSelects ) ) {
$.data( this, "plugin_" + chainSelects, new Plugin( this, options ) );
}
});
// chain jQuery functions
return this;
};
})( jQuery, window, document );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment