Skip to content

Instantly share code, notes, and snippets.

@FZambia
Created November 17, 2012 17:44
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save FZambia/4098067 to your computer and use it in GitHub Desktop.
Save FZambia/4098067 to your computer and use it in GitHub Desktop.
jquery nested selects
/**
*
* usage: $('#select-container').nested({url:'/path/to/backend/which/returns/options/'})
*
*/
(function($){
$.fn.extend({
//pass the options variable to the function
nested: function(options) {
//Set the default values
var defaults = {
url: '/',
hide:true,
empty:''
}
var options = $.extend(defaults, options)
var set_none = function(select) {
select.find('option[value=""]').attr('selected',true);
}
var set_disable = function(select) {
select.attr('disabled',true);
}
var clean = function(selects) {
selects.each(function(){
set_none($(this));
set_disable($(this));
})
}
var fill_select = function(next_select, data) {
var select = $(next_select);
var selected = select.find('option:selected');
select.find('option[value!=""]').not(selected).remove();
var options = '';
$.each(data, function(){
var value = this[0];
var text = this[1];
if (value==select.val()) {
$.noop;
} else {
options+='<option value="'+value+'">'+text+'</option>';
}
})
select.append($(options));
}
var get_options = function(name, id, next_select) {
if (id===options.empty) {
return;
}
$.post(options.url, {name:name, id:id}, function(data) {
fill_select(next_select, data);
}, "json");
}
var update = function(current_select, next_select) {
if (next_select==undefined) {
return false;
}
var name = $(current_select).attr('name');
var id = $(current_select).val();
get_options(name, id, next_select);
}
var initialize = function(selects) {
selects.each(function(index){
update($(this), selects.get(index+1));
})
}
var redisable = function(selects) {
var limit = false;
selects.each(function(index){
if (limit===true) {
$(this).attr('disabled',true);
set_none($(this));
if (options.hide===true) {
$(this).parent().fadeOut();
}
} else {
$(this).attr('disabled',false);
if (options.hide===true) {
$(this).parent().fadeIn();
}
}
value = $(this).val();
if (value===options.empty) {
limit = true;
}
})
}
var listen = function(selects) {
selects.each(function(index){
$(this).bind('change',function(){
update($(this), selects.get(index+1));
clean(selects.slice(index+1));
redisable(selects);
})
})
}
return this.each(function() {
var container = $(this);
var selects = container.find('select');
initialize(selects);
redisable(selects);
listen(selects);
});
}
})
})
(jQuery);
@gborle
Copy link

gborle commented Jul 27, 2017

How to integrate this plugin? Is it about select box inside another select box?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment