How to limit the number of selected checkboxes?

To limit the selection of checkboxes to a specific number, you can use JavaScript to handle the checkbox click events and prevent further selections once the limit is reached. Here’s an example of how you can achieve this:


<!DOCTYPE html>
<html lang="en">

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Checkbox Limit</title>

    <h2>Select up to 2 checkboxes:</h2>
    <input type="checkbox" class="checkbox"> Checkbox 1
    <input type="checkbox" class="checkbox"> Checkbox 2
    <input type="checkbox" class="checkbox"> Checkbox 3
    <input type="checkbox" class="checkbox"> Checkbox 4

    <script src="script.js"></script>


JavaScript (script.js):

// Get all checkboxes
const checkboxes = document.querySelectorAll('.checkbox');
let checkedCount = 0; // Variable to track the number of checked checkboxes

checkboxes.forEach(function(checkbox) {
    checkbox.addEventListener('change', function() {
        if (this.checked) {
            checkedCount++; // Increment the count when a checkbox is checked
        } else {
            checkedCount--; // Decrement the count when a checkbox is unchecked

        // Allow only 2 checkboxes to be checked
        if (checkedCount > 2) {
            this.checked = false; // Uncheck the checkbox if the limit is exceeded
            checkedCount--; // Decrement the count to maintain the limit

In this example, each checkbox has a class of “checkbox”. The JavaScript code adds an event listener to each checkbox, monitoring the “change” event. When a checkbox is checked, it increments the checkedCount variable. If the count exceeds 2, the checkbox is unchecked, and the count is decremented to maintain the limit of 2 checkboxes. This prevents users from selecting more than 2 checkboxes.