Last active
September 19, 2020 16:43
-
-
Save mcaskill/df6e703178d81c813f2f4b01818a315c to your computer and use it in GitHub Desktop.
JS : Toggle a range of checkboxes using the shift-key
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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