Day10 of #100DaysOfCode

Hii folks 🙌

Today I have completed the 10th video of JavaScript30!

Project 10: Hold Shift to Check Multiple Checkboxes



Hold Shift to Check Multiple Checkboxes

So, let’s start by logging in to the console!!

  • We can console.log what we query selected in order to check if we selected the correct elements
let checkbox = document.querySelectorAll('input[type="checkbox"]');
  • The checkbox is an array of input elements so we can add an event listener for each element by looping through them
checkbox.forEach(input => input.addEventListener('click', handleCheck));
  • We can console.log the event to check the event listener
function handleCheck(e){
  • Now we create a variable that stores which element was checked
let lastChecked;function handleCheck(e){
lastChecked = this;
  • Check if the shift key was pressed down and the checkbox has been checked!!
function handleCheck(e){
if(e.shiftKey && this.checked){ }lastChecked = this;
  • Create a checking variable with default value false and loop through each checkbox element.
  • If the checkbox element is equal to lastChecked value or the element that was shift clicked, the variable value is set to the opposite value
  • If the variable value is true, the checkbox is checked, which is done by the following code!
let lastChecked;function handleCheck(e) {
let inBetween = false; if (e.shiftKey && this.checked) { // loop over every single checkbox
checkboxes.forEach(checkbox => {
if (checkbox === this || checkbox === lastChecked) {
inBetween = !inBetween;
} if (inBetween) {
checkbox.checked = true;
}); }lastChecked = this;

Today I learned (T-I-L):

  • e.shiftKey && this.checked — THIS WAS JUST AWESOME

That is all for Day10 ✅

Thanks for reading, See you tomorrow!



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store