Skip to content

Instantly share code, notes, and snippets.

@cman81
Forked from jmcd/multiSelectToCheckboxes.js
Created June 16, 2016 08:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save cman81/ef1ad79cff899c01160ba7d77f761f13 to your computer and use it in GitHub Desktop.
Save cman81/ef1ad79cff899c01160ba7d77f761f13 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 $container = $ul.prev().andSelf().wrapAll("<div class='multiselect-to-checkboxes'></div>");
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() {
var $option = $(this).parents('.multiselect-to-checkboxes').find('select option').eq(index);
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);
@cman81
Copy link
Author

cman81 commented Jun 16, 2016

Example:

<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();

To get this:

<div class="multiselect-to-checkboxes">
  <select multiple="" id="all-local-resources"><!-- now hidden -->
    ...
  </select>

  <ul><!-- list of checkboxes (with labels) -->
    ...
  </ul>
</div>

@xnhinzkyx
Copy link

Thanks! Forked it.

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