Skip to content

Instantly share code, notes, and snippets.

@dantetesta
Created March 30, 2023 11:00
Show Gist options
  • Save dantetesta/066c5120742e9e0d81dcf6751c61462f to your computer and use it in GitHub Desktop.
Save dantetesta/066c5120742e9e0d81dcf6751c61462f to your computer and use it in GitHub Desktop.
<script>
function limitCheckboxSelection(CheckBoxName, hidden_limit_field) {
const checkboxes = document.querySelectorAll(`input[name="${CheckBoxName}"]`);
const hiddenField = document.querySelector(`input[name="${hidden_limit_field}"]`);
const limit = parseInt(hiddenField.value, 10);
checkboxes.forEach((checkbox) => {
checkbox.addEventListener('change', () => {
const checkedCount = document.querySelectorAll(`input[name="${CheckBoxName}"]:checked`).length;
if (checkedCount > limit) {
checkbox.checked = false;
}
});
});
}
const checkboxSetups = [
{ CheckBoxName: "nome-do-checkbox-1", hidden_limit_field: "limite-1" },
{ CheckBoxName: "nome-do-checkbox-1", hidden_limit_field: "limite-2" },
];
checkboxSetups.forEach((setup) => {
limitCheckboxSelection(setup.CheckBoxName, setup.hidden_limit_field);
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment