skip to Main Content

I am toggling classes on a table to hide specific columns, based on checkboxes that are selected by the user above the table. The checkboxes have IDs "product_1", "product_2" etc.

There are 4 columns in the table, so I made 4 functions that do the toggling:

  const toggleFirst = document.getElementById('product_1').addEventListener('click', () => {
    document.querySelector('#compare-table').classList.toggle('tb-compare-hide-1');
  });
  const toggleSecond = document.getElementById('product_2').addEventListener('click', () => {
    document.querySelector('#compare-table').classList.toggle('tb-compare-hide-2');
  });
  const toggleThird = document.getElementById('product_3').addEventListener('click', () => {
    document.querySelector('#compare-table').classList.toggle('tb-compare-hide-3');
  });
  const toggleFourth = document.getElementById('product_4').addEventListener('click', () => {
    document.querySelector('#compare-table').classList.toggle('tb-compare-hide-4');
  });

The classes that are toggled then control the showing/hiding.

I have this working, but I have 4 CSS classes, and 4 JS functions, that are basically doing the same thing but with a different checkbox relating to a different class.

Can I achieve this with fewer repetitive classes and functions?

2

Answers


  1. You can remove the ID from the checkboxes and use classes instead. To map the checkboxes to the column you can use the data attribute`

    <input type="checkbox" class="product" data-column-number="1">
    <input type="checkbox" class="product" data-column-number="2">
    <input type="checkbox" class="product" data-column-number="3">
    <input type="checkbox" class="product" data-column-number="4">
    
    const elementCompareTable = document.querySelector('#compare-table');
    
    document.querySelector('.product').addEventListener('click', (event) => {
        const numberTarget = event.target.dataset.columnNumber;
        elementCompareTable.classList.toggle(`tb-compare-hide-${numberTarget}`);
      });
    
    Login or Signup to reply.
  2. You should check for the existence of an element before trying to use it.

      const compareTable = document.querySelector('#compare-table');
      let arr = [], el;
    
      const foo = (el, i) => {
        if (el) {
          el.addEventListener("click", () => {
            compareTable.classList.toggle(`tb-compare-hide-${i}`);
          })
          arr.push(el);
        }
      }
    
      if (compareTable) {
        for (let i=1; i<5; i++) {
          el = document.getElementById(`product_${i}`);
          foo(el, i);
        }
      }
    
      // you can then use the array indexes to reference the elements
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search