Skip to content

Instantly share code, notes, and snippets.

@mcaskill
Last active September 19, 2020 16:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mcaskill/df6e703178d81c813f2f4b01818a315c to your computer and use it in GitHub Desktop.
Save mcaskill/df6e703178d81c813f2f4b01818a315c to your computer and use it in GitHub Desktop.
JS : Toggle a range of checkboxes using the shift-key
(function () {
const table = document.getElementById('my-table');
let lastInput = null;
table.addEventListener('click', function (event) {
const currInput = event.target;
if (currInput.type !== 'checkbox') {
return;
}
if (event.shiftKey && lastInput !== null && lastInput !== currInput) {
const inputs = table.querySelectorAll('input[type="checkbox"]');
lastInput.checked = currInput.checked;
lastInput.dispatchEvent(new Event('change', {
bubbles: true,
cancelable: true
}));
let inBetween = false;
inputs.forEach(function (input) {
if (input === lastInput || input === currInput) {
inBetween = !inBetween;
} else if (inBetween) {
input.checked = currInput.checked;
input.dispatchEvent(new Event('change', {
bubbles: true,
cancelable: true
}));
}
});
}
lastInput = currInput;
}, {
passive: true
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment