Skip to content

Instantly share code, notes, and snippets.

@EmmanuelBeziat
Last active November 27, 2020 18:31
Show Gist options
  • Save EmmanuelBeziat/09a05aa57649e0dff785570d19e62c5d to your computer and use it in GitHub Desktop.
Save EmmanuelBeziat/09a05aa57649e0dff785570d19e62c5d to your computer and use it in GitHub Desktop.
Limit checkboxes
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