Skip to content

Instantly share code, notes, and snippets.

@PureForm
Created January 6, 2012 04:01
Show Gist options
  • Save PureForm/1568900 to your computer and use it in GitHub Desktop.
Save PureForm/1568900 to your computer and use it in GitHub Desktop.
CM.CheckboxRangeCheck = function (formID,checkboxIdPrefix,checkboxIdRegex) {
var lastCheckboxClickedID = "";
$("#" + formID + " input[type=checkbox]").on("click",function(e) {
if (e.shiftKey && (lastCheckboxClickedID !== "") && $(this).prop("checked") && $("#" + lastCheckboxClickedID).prop("checked")) {
var startIndex = parseInt(checkboxIdRegex.exec(lastCheckboxClickedID)[1],10);
var endIndex = parseInt(checkboxIdRegex.exec($(this).prop("id"))[1],10);
if (endIndex < startIndex) {
var tmp = startIndex;
startIndex = endIndex;
endIndex = tmp;
}
var i = startIndex;
while (true) {
++i;
if (i > endIndex) {
break;
}
$("#" + checkboxIdPrefix + i.toString()).prop("checked",true);
}
}
lastCheckboxClickedID = $(this).attr("id");
});
return {
method: function() {
}
};
};
@brianreavis
Copy link

If you wanted... you could change it up a tiny smidge for it to be easier to use. Totally untested:

$.fn.checkboxRange = function() {
    var checkboxes  = [];
    var lastChecked = null;

    for (var i = 0; i < this.length; i++) {
        checkboxes.push(this[i]);
    }

    $(this).on("click",function(e) {
        if (e.shiftKey && (lastChecked !== null) && $(this).prop("checked") && $(lastChecked).prop("checked")) {

            var startIndex  = checkboxes.indexOf(this);
            var endIndex    = checkboxes.indexOf(lastChecked);

            if (endIndex < startIndex) {
                var tmp     = startIndex;
                startIndex  = endIndex;
                endIndex    = tmp;
            }

            for (var i = startIndex + 1; i <= endIndex; i++) {
                $(checkboxes[i]).prop("checked",true);
            }
        }

        lastChecked = this;
    });

    return this;
};

In theoryyyy... you could then do:

$('input.email-address').checkboxRange();

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