Skip to content

Instantly share code, notes, and snippets.

@mishterk
Last active March 27, 2023 01:43
Show Gist options
  • Save mishterk/d98950e948afda9ce2e4f9651ab36a0f to your computer and use it in GitHub Desktop.
Save mishterk/d98950e948afda9ce2e4f9651ab36a0f to your computer and use it in GitHub Desktop.

Limit number of checkable boxes

Here is a simple JavaScript code snippet that limits the number of checkboxes that can be checked at any one time. In this example, the limit is set to 3 checkboxes.

This code creates a simple HTML page with 5 checkboxes. When a user tries to select more than the allowed number of checkboxes (in this case, 3), an alert will be displayed, and the latest checkbox selection will be undone.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Checkbox Limit</title>
</head>
<body>
<input type="checkbox" class="limited-checkbox"> Checkbox 1
<input type="checkbox" class="limited-checkbox"> Checkbox 2
<input type="checkbox" class="limited-checkbox"> Checkbox 3
<input type="checkbox" class="limited-checkbox"> Checkbox 4
<input type="checkbox" class="limited-checkbox"> Checkbox 5
<script>
const maxChecked = 3;
const checkboxes = document.querySelectorAll('.limited-checkbox');
checkboxes.forEach(checkbox => {
checkbox.addEventListener('change', function() {
let checkedCount = 0;
checkboxes.forEach(box => {
if (box.checked) {
checkedCount++;
}
});
if (checkedCount > maxChecked) {
this.checked = false;
alert(`You can only select up to ${maxChecked} checkboxes at a time.`);
}
});
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment