How to Allow Only One Checkbox to Be Checked in HTML

How to Allow Only One Checkbox to Be Checked in HTML

Using two different solutions
Ferenc Almasi β€’ Last updated 2024 January 31 β€’ Read time 5 min read
Learn how you can allow only one checkbox to be selected at a time in HTML using JavaScript event listeners.

When working with multiple checkboxes, a common use case is to limit the number of selectable options, preventing users from selecting more options than allowed. For example, you may have the following group of checkboxes where you only want a maximum of two options to be selected:

In this tutorial, we will take a look at how this can be achieved in HTML with the use of event listeners in JavaScript.

If you need to allow only one checkbox to be selected, use a radio group instead.


Creating the HTML Markup

First, we need to create the input group in HTML. To do this, create the following layout in your HTML file:

Copied to clipboard! Playground
<span>You can only select up to two options.</span>
<div>
    <label for="html">
        <input type="checkbox" value="html" id="html" />
        HTML
    </label>
    <label for="javascript">
        <input type="checkbox" value="javascript" id="javascript" />
        JavaScript
    </label>
</div>
Create the input group in HTML

To separate the input group from the rest of the layout, wrap it inside a div, which we will style shortly. To make the inputs accessible, wrap them inside a label. We can match a label with an input using the for attribute, which references the element's id.

Make sure you caption the group to make it clear that users can only select a limited number of options.

To display the inputs below each other, we can set the display of the wrapping div to flex, and set the flex-direction to column:

Copied to clipboard!
div {
    display: flex;
    flex-direction: column;
}
Align the inputs in CSS

Allow Only a Limited Number of Checkboxes to be Checked

To get everything working, we need to attach a click event listener to the checkboxes in JavaScript. To avoid creating a separate listener for each checkbox, we can use event delegation:

Copied to clipboard! Playground
const maxChecks = 2
let selectedCount = 0

document.querySelector('div').addEventListener('click', event => {
  if (event.target.type === 'checkbox') {
    selectedCount = event.target.checked
      ? selectedCount + 1
      : selectedCount - 1
  }

  if (selectedCount >= maxChecks) {
    [...document.querySelectorAll('input:not(:checked)')].forEach(input => input.disabled = true)
  } else {
    [...document.querySelectorAll('input')].forEach(input => input.disabled = false)
  }
})
Allow only two checkboxes to be selected at a time

In the example above, we set the maximum number of available options to two using the maxChecks variable. We also need to keep track of the number of selected checkboxes. This will be tracked in the selectedCount variable. Inside the event listener, we need to implement the following logic:

  • Line 4: We attach the event listener to the div container so that we can delegate it to the checkboxes.
  • Line 5: To determine if a checkbox was clicked, we can check if event.target.type is checkbox.
  • Lines 6-8: In case a checkbox was clicked, we need to either increase or decrease the selectedCount variable. This is done using a ternary operator. If the checkbox is checked (event.target.checked will be true), then we increase the count by one; otherwise, we decrease it.
  • Line 11: If the selectedCount reaches maxChecks, we need to select all checkboxes that are unchecked and disable them using the disabled property. We can select them using the :not(:checked) pseudo-class.
  • Line 14: In case we haven't reached the maximum allowed checkboxes, we re-enable every input by setting input.disabled to false. Note that since querySelectorAll returns a NodeList, we need to use the spread operator to convert it into a regular array so that we can use forEach.
Looking to improve your skills? Check out our interactive course to master JavaScript from start to finish.
Master JavaScriptinfo Remove ads

Semantically Correct Way For Single Selects

In case you need users to select only one option from many, the semantically correct way to achieve this is by using a radio group:

Copied to clipboard! Playground
<div>
    <label for="html">
        <!-- Use the `checked` property if you want one of the options to be preselected -->
        <input type="radio" value="html" id="html" name="topic" checked />
        HTML
    </label>
    <label for="javascript">
        <input type="radio" value="javascript" id="javascript" name="topic" />
        JavaScript
    </label>
</div>
Creating a group of radio buttons in HTML

Radio buttons can be grouped together, restricting users to select only one option. In the example below, you can experiment with how the code above will be presented to the end user.

The right column also includes a clear button that can be used to clear previous answers in case you want the fields to be optional. This way, you can remove accidental selections with the use of a button. The following JavaScript code is executed on click:

Copied to clipboard!
document.querySelector('button').addEventListener('click', () => {
    [...document.querySelectorAll('input[type="radio"]')].forEach(input => input.checked = false)
})
Clearing previously selected radio buttons

Conclusion

In conclusion, always use a radio group when you need to restrict the number of options to only one. Use checkboxes only when you need to enable users to select multiple options, even if you need to limit the number of selections to a maximum. You can try out the functionality with the editor below.

  • index.js index.js
  • styles.css styles.css
  • index.html index.html
Refresh

Is there anything you think this tutorial is missing? Let us know in the comments below! If you would like to learn more about JavaScript, make sure you check out our roadmap below. Thank you for reading, happy coding! πŸ‘¨β€πŸ’»

Master JavaScript
Did you find this page helpful?
πŸ“š More Webtips
Mentoring

Rocket Launch Your Career

Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies:

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.