jeudi 20 juillet 2023

How to uncheck all checkboxes in a single click?

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?




Aucun commentaire:

Enregistrer un commentaire