skip to Main Content

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


  1. You could simplify your logic by putting your checkboxes into an array and getting the range of checkboxes to check:

    // collect all the checkboxes into an array for easier handling
    
    const checkboxes = [...document.querySelectorAll('.inbox input[type="checkbox"]')];
    
    let lastChecked;
    
    function handleCheck(e) {
      
      if (e.shiftKey) {
    
        // we should set all checkboxes in the range with this value (including the last checked)
        const checked = lastChecked?.checked;
    
        // get the range of checkboxes to check between lastChecked and this (including both)
        const range = [lastChecked, this].map(check => checkboxes.indexOf(check)).sort((a, b) => a - b);
    
        // get checkboxes in the range and check them
        checkboxes.slice(range[0], range[1] + 1).forEach(check => check.checked = checked);
    
      }
       
    
      lastChecked = this;
    }
    
    checkboxes.forEach(checkbox =>
      checkbox.addEventListener('click', handleCheck)
    );
    p{
    display:inline-block;
    margin:0;
    }
    <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>
    Login or Signup to reply.
  2. You can add this to your handleCheck :

    else if (e.shiftKey && !this.checked) {
      // If shift key is down and checkbox is being unchecked
      // loop over every single checkbox and deselect the ones in between
      checkboxes.forEach(checkbox => {
        if (checkbox === this || checkbox === lastChecked) {
          inBetween = !inBetween;
        }
    
        if (inBetween) {
          checkbox.checked = false;
        }
      });
    }
    
    Login or Signup to reply.
  3. 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 between lastShiftCheck and the clicked checkbox (inclusive).

    Here’s a modification to your existing code:

    const checkboxes = document.querySelectorAll('.inbox input[type="checkbox"]');
    let lastChecked;
    let lastShiftCheck;
    
    function handleCheck(e) {
      let inBetween = false;
    
      // Deselecting operation
      if (this.checked === false) {
        checkboxes.forEach(checkbox => {
          if ((checkbox === lastShiftCheck || checkbox === this) && lastShiftCheck) {
            inBetween = !inBetween;
          }
          if (inBetween) {
            checkbox.checked = false;
          }
        });
      } else if (e.shiftKey && this.checked) { // Selecting operation
        checkboxes.forEach(checkbox => {
          if (checkbox === this || checkbox === lastChecked) {
            inBetween = !inBetween;
          }
          if (inBetween) {
            checkbox.checked = true;
          }
        });
        lastShiftCheck = this; // Store the last shift clicked checkbox
      }
    
      lastChecked = this;
    }
    
    checkboxes.forEach(checkbox => checkbox.addEventListener('click', handleCheck));
    

    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.

    Login or Signup to reply.
  4. it seems you do not check the document is ready.

    I just wrapped your code into a DOMContentLoaded Eventlistener and it works.

    document.addEventListener("DOMContentLoaded", () => {
    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)
      );
    });
    

    As you cann see there isn’t more to add.
    Hope this will help.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search