In this installment of Wes Bos’ js#30, the challenge is to check multiple checkboxes when shift-clicking
I had a go at it beforehand; I was populating an array of indexes of checked checkboxes, then trying to use the lowest & highest indexes to target indexes in-between. Problem with this approach was that the index of the checked checkbox was also being pushed to the array and thereby de-railing the utility of the lowest & highest. On reflection I think could be made to work, TBD, to be revisited
Bos’s solution was in any case certainly more efficient:
function handleCheck(e) {
let isBetween = false;
if (e.shiftKey && this.checked) { // first, check if click is checking rather than un-checking
/*
then, iterate thru all checkboxes, and when either the one just checked (this) or
the 'lastChecked' is found, toggle *and sustain the value of isBetween for each
successive checkbox*, until iteration finds the other (this or lastChecked) ...
i.e., this is sort of functioning like a while loop
*/
checkboxes.forEach(checkbox => {
if (checkbox === this || checkbox === lastChecked) {
isBetween = !isBetween;
}
if (isBetween) {
checkbox.checked = true;
}
}); // forEach
} // if shifting ...
lastChecked = this; // update value of lastChecked
}; // handleCheck
p.s. this led me into some interesting reading on Booleans, the not operator, and uses of the ‘not not operator’