Let’s say you have multiple checkboxes on a page and for a better user experience you provide a select all checkbox at the top of all the checkboxes so that the user can select all checkboxes(items) in a single click if he wants. How can you do that in JavaScript?
Well, In this article, I will show you a very easy and efficient method that you can use to select and deselect all checkboxes in a single click using JavaScript.
We will achieve this in the below three steps:
- Add the
onchange
event to the selectAll checkbox(top one). This will trigger a custom function whenever the checkbox is checked or unchecked. - Select all the checkboxes using a DOM method such as
querySelectorAll()
orgetElementsByClassName()
, etc. - Use the
checked
property to check if the selectAll checkbox is checked or not. If it is checked, make all the checkboxes checked otherwise make them unchecked.
See the following working example:
Example:
var allCheckboxes = document.querySelectorAll('input[type=checkbox]'); function checkUncheck(selectAll){ if(selectAll.checked){ for(let i=1;i<allCheckboxes.length;i++){ allCheckboxes[i].checked = true; } }else{ for(let i=1;i<allCheckboxes.length;i++){ allCheckboxes[i].checked = false; } } } // i starts with 1 as we want to exclude the top checkbox
You can use any DOM method to select or deselect all the checkboxes that you want. The basic concept in all the cases remains the same.
The only thing that changes is the way you iterate through all the checkboxes.
In the following example, we have assigned a class lang
to all the checkboxes that we want to select on a single click. Now, to access these checkboxes we have used the getElementsByClassName()
method instead of the querySelectorAll()
.
See the following working example:
Example:
var allCheckboxes = document.getElementsByClassName('lang'); function checkUncheck(selectAll){ if(selectAll.checked){ for(let i=0;i<allCheckboxes.length;i++){ allCheckboxes[i].checked = true; } }else{ for(let i=0;i<allCheckboxes.length;i++){ allCheckboxes[i].checked = false; } } } // i starts with 0 as it's already not considering the top checkbox
Thanks for reading.