This is day 10 in my #javascript30 journey. This is the free course from Wes Bos that lets you brush up on your JavaScript skills via 30 projects.
Yesterday we covered the very click-baity 14 Must know Dev Tools Tricks. You can keep track of all the projects we’re building here.
Today we’re exploring how to hold shift to check multiple checkboxes.
Day 10 - Hold Shift to Check Multiple Checkboxes
The goal for today is that when you click one check box then hold shift and click another one the app will automatically select all of the checkboxes between the first and second check boxes.
e.g.
To do this we will need to:
- Select all checkboxes.
- Listen for when any checkbox gets clicked or changed.
- Save a reference to the first checked checkbox.
- Check if the shift key is pressed AND the new check box is being checked (not unchecked).
- Loop through all checkboxes in between the selected checkboxes and set them to checked.
This boils down to:
const checkboxes = document.querySelectorAll('.inbox input[type="checkbox"]')
function handleCheck(e) {
let inBetween = false
if (e.shiftKey && this.checked) {
checkboxes.forEach(checkbox => {
if (checkbox === this || checkbox === lastChecked)
inBetween = !inBetween
if (inBetween){
checkbox.checked = true
}
})
}
lastChecked = this
}
checkboxes.forEach(checkbox => checkbox.addEventListener('click', handleCheck))
It works perfectly. I can check multiple checkboxes at the click of a mouse (and a key).
Clear Selection
As some added functionality, I wanted to add a ‘Clear Selected’ button.
To do this I would need to:
- Add a button to the interface.
- Listen for the click event on the button.
- Loop through all checkboxes and uncheck them.
This turned out like:
function handleClear(e) {
checkboxes.forEach(checkbox => checkbox.checked = false)
}
document.getElementById('clear').addEventListener('click', handleClear)
Now that everything has been done I have pushed this project live to a Firebase project. You can view it live here.
You can keep track of all the projects in this JavaScript30 challenge here.