Skip to content

Instantly share code, notes, and snippets.

@mtayseer
Forked from jmcd/multiSelectToCheckboxes.js
Last active July 9, 2019 07:42
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mtayseer/5743199 to your computer and use it in GitHub Desktop.
Save mtayseer/5743199 to your computer and use it in GitHub Desktop.
(function($) {
function addUL(parent) {
var $ul = $("<ul/>");
var baseId = "_" + $(parent).attr("id");
$(parent).children("option,optgroup").each(function(index, tag) {
if (tag.tagName.toLowerCase() === "option") {
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>");
} else {
var optGroupUL = addUL(this);
var $li = $('<li>' + this.label + '</li>').appendTo($ul)
optGroupUL.appendTo($ul);
}
});
return $ul;
}
var methods = {
init: function() {
var ul = addUL(this);
ul.insertAfter(this);
ul.addClass('multiple_selection');
$(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);
@abbasadel
Copy link

demo plz?

@mkkmail
Copy link

mkkmail commented Oct 8, 2014

Hi. how can i use it?

@cman81
Copy link

cman81 commented Jun 16, 2016

For this:

<select multiple="" id="all-local-resources">
  <option value="brownfields">Brownfields and Re-development and Industrial Cleanup</option>
  <option value="climate">Climate Change</option>
  <option value="conservation">Conservation and Alternative Energy</option>
  <option value="drinking">Drinking Water and Wastewater</option>
</select>

Add this:
$('#all-local-resources').multiSelectToCheckboxes();

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