JavaScript: making sure at least one Checkbox is Checked

avatar
Borislav Hadzhiev

Last updated: Mar 7, 2024
4 min

banner

# JavaScript: making sure at least one Checkbox is Checked

To make sure at least one checkbox is checked:

  1. Select all input elements with type of checkbox on the page.
  2. Iterate over the elements using Array.some() and use the checked property to test if each checkbox has been checked.
  3. Use an if statement to check if the condition is met.

Here is the HTML for the example.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <form id="fruit-form"> <input type="checkbox" id="apple" name="apple" value="apple" /> <label for="apple">Apple</label> <br /> <input type="checkbox" id="banana" name="banana" value="banana" /> <label for="banana">Banana</label> <br /> <span> <input type="checkbox" id="kiwi" name="kiwi" value="kiwi" /> <label for="kiwi">Kiwi</label> </span> <br /> <span> <input type="checkbox" id="mango" name="mango" value="mango" /> <label for="mango">Mango</label> </span> <br /> <br /> <button type="submit">Submit</button> <h2 id="validation-message"></h2> </form> <script src="index.js"></script> </body> </html>
The code for this article is available on GitHub

And here is the related JavaScript code.

index.js
// ๐Ÿ‘‡๏ธ find the first selected checkbox function findFirstSelectedCheckbox(checkboxes) { return Array.from(checkboxes).find( checkbox => checkbox.checked, ); } // ๐Ÿ‘‡๏ธ get an array of all selected checkboxes function findAllSelectedCheckboxes(checkboxes) { return Array.from(checkboxes).filter( checkbox => checkbox.checked, ); } // ๐Ÿ‘‡๏ธ check if at least one checkbox is checked function atLeastOneCheckboxChecked(checkboxes) { return Array.from(checkboxes).some( checkbox => checkbox.checked, ); } const form = document.getElementById('fruit-form'); const checkboxes = document.querySelectorAll( 'input[type="checkbox"]', ); const validationMessage = document.getElementById( 'validation-message', ); // ๐Ÿ‘‡๏ธ check if at least one checkbox is checked when // submitting the form form.addEventListener('submit', event => { event.preventDefault(); if (!atLeastOneCheckboxChecked(checkboxes)) { console.log('None of the checkboxes are checked'); validationMessage.innerHTML = 'At least once checkbox must be checked'; return; } validationMessage.innerHTML = 'Form submitted successfully'; console.log('At least one checkbox is checked'); console.log(findFirstSelectedCheckbox(checkboxes)); console.log(findAllSelectedCheckboxes(checkboxes)); console.log(findAllSelectedCheckboxes(checkboxes).length); });

make sure at least one checkbox is checked

The code for this article is available on GitHub

Let's go over the code in the HTML file first.

We have 4 input elements that have their type attribute set to checkbox.

index.html
<input type="checkbox" id="apple" name="apple" value="apple" /> <label for="apple">Apple</label> <br />

Each checkbox has a label associated with it.

The id attribute of each input field has to correspond to the for attribute of the label so that the user can check a checkbox when the label text is clicked.

The input elements are wrapped in a form tag.

index.html
<form id="fruit-form"> <!-- ... --> </form>

The form has a button that has its type attribute set to submit.

index.html
<button type="submit">Submit</button>

When the button is clicked or the Enter key is pressed, the form's submit event is triggered.

Lastly, we have an h2 element that we'll use to render the validation message based on whether the user checked at least one checkbox before submitting the form.

index.html
<h2 id="validation-message"></h2>

At the start of our index.js file, we defined 3 functions.

We use the Array.from() method to convert the collection of HTML elements to an array to be able to use array methods, such as find(), filter() and some().

The first function takes the collection of checkboxes as a parameter and iterates over them using the Array.find() method.

index.js
function findFirstSelectedCheckbox(checkboxes) { return Array.from(checkboxes).find( checkbox => checkbox.checked, ); }

The function returns the first checkbox that is checked or undefined if none of the checkboxes are checked.

The second function uses the Array.filter() method to get an array containing the checkboxes that are checked.

index.js
function findAllSelectedCheckboxes(checkboxes) { return Array.from(checkboxes).filter( checkbox => checkbox.checked, ); }

If none of the checkboxes are checked, the array will be empty.

The third function uses the Array.some() method to check if at least one checkbox has been checked.

index.js
function atLeastOneCheckboxChecked(checkboxes) { return Array.from(checkboxes).some( checkbox => checkbox.checked, ); }

The Array.some() method will return true if at least one checkbox has its checked attribute set to true, otherwise, false is returned.

We then select the form element, the checkboxes and the validation message element.

index.js
const form = document.getElementById('fruit-form'); const checkboxes = document.querySelectorAll( 'input[type="checkbox"]', ); const validationMessage = document.getElementById( 'validation-message', );

We used the document.getElementById() method to select the form and the validation message elements by their IDs.

The code sample uses the document.querySelectorAll() method to select all input elements that have their type attribute set to checkbox.

You can tweak the selector to only select input elements with type set to checkbox within the specific form.

index.js
const checkboxes = document.querySelectorAll( '#fruit-form input[type="checkbox"]', );

The selector uses the id of the form element to only select checkboxes within the form.

You can also use the id values of the checkboxes to select them.

index.js
const checkboxes = document.querySelectorAll( '#apple, #banana, #kiwi, #mango', );

Notice that the selectors are separated by a comma.

The next step is to add a submit event listener to the form element.

index.js
form.addEventListener('submit', event => { event.preventDefault(); if (!atLeastOneCheckboxChecked(checkboxes)) { console.log('None of the checkboxes are checked'); validationMessage.innerHTML = 'At least once checkbox must be checked'; return; } validationMessage.innerHTML = 'Form submitted successfully'; console.log('At least one checkbox is checked'); console.log(findFirstSelectedCheckbox(checkboxes)); console.log(findAllSelectedCheckboxes(checkboxes)); console.log(findAllSelectedCheckboxes(checkboxes).length); });
The code for this article is available on GitHub

We used the event.preventDefault method to prevent the browser from refreshing the page.

The if statement uses the logical NOT (!) operator to negate the call to the function.

If none of the checkboxes have been checked, we render a message that at least one checkbox must be checked.

Otherwise, we render a message that the form has been submitted successfully.

Depending on your use case, you might or might not need to access the selected checkboxes.

If you need to get the first selected checkbox, call the findFirstSelectedCheckbox(checkboxes) function as shown in the code sample.

If you need to get an array of all selected checkboxes, call the findAllSelectedCheckboxes(checkboxes) function.

If you need to get the number of checkboxes that have been checked, access the length property on the array you got from the findAllSelectedCheckboxes() function.

index.js
console.log(findFirstSelectedCheckbox(checkboxes)); console.log(findAllSelectedCheckboxes(checkboxes)); console.log(findAllSelectedCheckboxes(checkboxes).length);

make sure at least one checkbox is checked

The code for this article is available on GitHub

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev