Last active
November 27, 2020 18:31
-
-
Save EmmanuelBeziat/09a05aa57649e0dff785570d19e62c5d to your computer and use it in GitHub Desktop.
Limit checkboxes
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
const setCheckboxLimit = (list, limit, warning = false) => { | |
if (!list) return | |
const checkboxes = list.querySelectorAll('input[type="checkbox"]') | |
if (!checkboxes.length) return | |
checkboxes.forEach(checkbox => checkbox.addEventListener('click', event => { | |
const checkedChecks = list.querySelectorAll('input[type="checkbox"]:checked') | |
if (checkedChecks.length >= limit + 1) { | |
event.preventDefault() | |
event.stopPropagation() | |
if (warning) { | |
alert(`You can’t select more than ${limit} choices`) | |
} | |
} | |
})) | |
} | |
document.addEventListener('DOMContentLoaded', () => { | |
setCheckboxLimit(document.querySelector('my-list'), 4) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment