Last updated: Mar 7, 2024
Reading timeยท4 min
To make sure at least one checkbox is checked:
input
elements with type
of checkbox
on the page.Array.some()
and use the checked
property
to test if each checkbox has been checked.if
statement to check if the condition is met.Here is the HTML for the example.
<!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>
And here is the related JavaScript code.
// ๐๏ธ 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); });
Let's go over the code in the HTML file first.
We have 4 input
elements that have their type
attribute set to checkbox
.
<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.
<form id="fruit-form"> <!-- ... --> </form>
The form
has a button that has its type
attribute set to submit
.
<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.
<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.
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.
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.
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.
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.
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.
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.
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); });
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.
console.log(findFirstSelectedCheckbox(checkboxes)); console.log(findAllSelectedCheckboxes(checkboxes)); console.log(findAllSelectedCheckboxes(checkboxes).length);
You can learn more about the related topics by checking out the following tutorials:
hidden
Div on Hover using JavaScript