Skip to content

Instantly share code, notes, and snippets.

@sumanthkumarc
Created November 22, 2016 12:02
Show Gist options
  • Save sumanthkumarc/adabd1b9a5b56ea8a40006815ab7a13f to your computer and use it in GitHub Desktop.
Save sumanthkumarc/adabd1b9a5b56ea8a40006815ab7a13f to your computer and use it in GitHub Desktop.
Adding all option for list of options
$('document').ready(function () {
// Below code takes care of adding All checkbox to options.
var i = 0;
$(".form-checkboxes").each(function () {
i++;
// Add events.all checkbox only if there are more than 2 options.
if ($(this).children().length > 2) {
// Adds the all checkbox
addAllCheckbox($(this), 'All');
// On click of All checkbox, check/uncheck all the options.
$(".form-checkboxes .form-checkall").change(function () {
// if All option is checked, check all the options.
if ($(this).prop("checked") == true) {
checkboxController($(this), true);
}
// if All option is un-checked,un-check all the options.
if ($(this).prop("checked") == false) {
checkboxController($(this), false);
}
});
// Takes care of unchecking the All option, if any child option is unchecked.
$(".form-checkboxes input:checkbox").change(function () {
if ($(this).prop("checked") == false) {
$(this).parents('.form-checkboxes').find(".form-checkall").prop('checked', false);
}
});
}
});
// Checks/unchecks all the options, depending on state passed to this function.
function checkboxController(allCheckbox, state) {
console.log(allCheckbox.parents('.form-checkboxes').find(".form-checkbox"));
allCheckbox.parents('.form-checkboxes').find("input:checkbox").each(function () {
$(this).prop('checked', state);
});
}
// Adds the all checkbox to option group
function addAllCheckbox(container, name) {
var checkbox_all = "<div class='form-item js-form-item form-type-checkbox js-form-type-checkbox checkbox'>";
checkbox_all += "<label for='checkbox-all' class='control-label option checkbox-all-label'>";
checkbox_all += "<input type= 'checkbox' value='All' class='checkbox-all form-checkbox form-checkall'>";
checkbox_all += name + "</label></div>";
container.prepend(checkbox_all);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment