Skip to content

Instantly share code, notes, and snippets.

@jmcd
Created April 2, 2012 15:52
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save jmcd/2284550 to your computer and use it in GitHub Desktop.
Save jmcd/2284550 to your computer and use it in GitHub Desktop.
jQuery plugin to convert multi-select HTML to checkbox list
(function($) {
var methods = {
init: function() {
var $ul = $("<ul/>").insertAfter(this);
var baseId = "_" + $(this).attr("id");
$(this).children("option").each(function(index) {
var $option = $(this);
var id = baseId + index;
var $li = $("<li/>").appendTo($ul);
var $checkbox = $("<input type='checkbox' id='" + id + "'/>").appendTo($li).change(function() {
if ($(this).is(":checked")) {
$option.attr("selected", "selected");
} else {
$option.removeAttr("selected");
}
});
if ($option.is(":selected")) {
$checkbox.attr("checked", "checked");
}
$checkbox.after("<label for='" + id + "'>" + $option.text() + "</label>");
});
$(this).hide();
}
};
$.fn.multiSelectToCheckboxes = function(method) {
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return methods.init.apply(this, arguments);
} else {
$.error('Method ' + method + ' does not exist on jQuery.multiSelectToCheckboxes');
}
};
})(jQuery);
@mtayseer
Copy link

mtayseer commented Jun 9, 2013

I forked it & added support for https://gist.github.com/mtayseer/5743199

@cman81
Copy link

cman81 commented Jun 16, 2016

I forked it and wrapped it in a container div, just in case the options were modified by something else. https://gist.github.com/cman81/ef1ad79cff899c01160ba7d77f761f13

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