I have made this program in javascript for select checkboxes using shift key? Now I want to deselct it by single click?
HTML
<div class="inbox">
<div class="item">
<input type="checkbox" />
<p>This is an inbox layout.</p>
</div>
<div class="item">
<input type="checkbox" />
<p>Check one item</p>
</div>
<div class="item">
<input type="checkbox" />
<p>Hold down your Shift key</p>
</div>
<div class="item">
<input type="checkbox" />
<p>Check a lower item</p>
</div>
<div class="item">
<input type="checkbox" />
<p>Everything in between should also be set to checked</p>
</div>
<div class="item">
<input type="checkbox" />
<p>Try do it without any libraries</p>
</div>
</div>
javascript for select the checkbox
const checkboxes = document.querySelectorAll(
'.inbox input[type="checkbox"]'
);
let lastChecked;
function handleCheck(e) {
//for selecting the checkboxes
let inBetween = false;
// Check if they had the shift key down
// AND check that they are checking it
if (e.shiftKey && this.checked) {
// go ahead and do what we please
// loop over every single checkbox
checkboxes.forEach(checkbox => {
console.log(checkbox);
if (checkbox === this || checkbox === lastChecked) {
inBetween = !inBetween;
console.log('Starting to check them in between!');
}
if (inBetween) {
checkbox.checked = true;
}
});
}
lastChecked = this;
}
checkboxes.forEach(checkbox =>
checkbox.addEventListener('click', handleCheck)
);
Now I want after selecting with shift key when I click on a selected checkbox then the selected checkboxes which comes after that should be unchecked in a single click?
4
Answers
You could simplify your logic by putting your checkboxes into an array and getting the range of checkboxes to check:
You can add this to your handleCheck :
You could add a new variable, say
lastShiftCheck
to store the last checkbox that was checked with shift key. Now when you click on a checkbox without the shift key and it is checked, the code will uncheck all checkboxes betweenlastShiftCheck
and the clicked checkbox (inclusive).Here’s a modification to your existing code:
This code will now deselect all the checkboxes between the last checkbox that was checked with shift and the current clicked checkbox, if the current clicked checkbox is being unchecked.
it seems you do not check the document is ready.
I just wrapped your code into a DOMContentLoaded Eventlistener and it works.
As you cann see there isn’t more to add.
Hope this will help.