Is there a way to efficiently access checkboxes by their IDs and toggle classes without the need for redundant classes and functions?

In my current project, I have set up functionality to toggle classes on a table for hiding specific columns. This is determined by checkboxes selected by the user above the table, each checkbox having its own unique ID like "product_1", "product_2", and so on.

Since there are 4 columns in the table, I created individual functions for 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 toggled classes are responsible for controlling the visibility of columns.

Although this setup is functional, I am aware that I essentially have repetitive CSS classes and JavaScript functions catering to each checkbox's unique class. I'm interested in exploring more efficient methods with fewer repetitions. Any suggestions?

Answer №1

If you want to simplify your code, consider using classes instead of IDs for checkboxes. You can associate each checkbox with a specific column using the `data` attribute.

<input type="checkbox" class="item" data-column-index="1">
<input type="checkbox" class="item" data-column-index="2">
<input type="checkbox" class="item" data-column-index="3">
<input type="checkbox" class="item" data-column-index="4">
const compareTable = document.querySelector('#comparison-table');

document.querySelectorAll('.item').forEach((checkbox) => {
    checkbox.addEventListener('click', (event) => {
        const columnIndex = event.target.dataset.columnIndex;
        compareTable.classList.toggle(`hide-column-${columnIndex}`);
    });
});

Answer №2

Before attempting to utilize an element, it is essential to verify its existence first.

  const compareTable = document.querySelector('#compare-table');
  let arr = [], el;

  const checkAndAddEventListener = (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}`);
      checkAndAddEventListener(el, i);
    }
  }

  // The array indexes can be used to access the elements afterwards

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ensure that all lists are aligned on the left side, from the numbers to

Trying to implement a solution for aligning numbers and text in an ordered list within a border. Found a helpful answer on Stack Overflow: Left align both list numbers and text Encountering an issue where long content in one list item overlaps into the n ...

Node.js tutorial: Building routes with regex and implementing redirects

Can anyone provide guidance on how to utilize route and redirect URLs with parameters in Node.js using Express? If the URL is xyz/?s=test, it should redirect to indexRouter. If the URL is xyz/, it should also redirect to indexRouter. I'm facing issu ...

Is there a way to assign a role to a user without requiring them to send a message beforehand?

I've been searching for a solution to this issue, but all I could find were instructions on how to assign a server role to someone who has interacted in some way. Is there a way to locate a specific user on a server and assign a role to them without ...

AngularJS JSON data computation

As I delve into learning angularjs (not 2), one of the challenges I face is calculating the total amount for a customer order. The data I'm working with is structured as follows: var clients = [ { id: 1, jo ...

Submitting an AJAX form redirects to a different page instead of keeping the user on the current page

I've encountered an issue with my popup ajax form. Instead of staying on the same page after data submission, it redirects me to send.php file. This behavior is different from another website where I successfully implemented a similar form. I'm n ...

Guide to Angular Directives: Assigning Attributes to innerHTML

Looking to add attributes to the inner HTML myTemplate.html <div class="custom-template"></div> HTML <template></template> directive app.directive('template', ['$compile', function($compile) { retur ...

Instructions on utilizing the transpiled "main.js" file using gulp

As a novice in Angularjs 1.0, I encountered issues with my script and decided to use gulp to compile ec6 to ec5 by implementing the code provided below. The compilation process generated the file main.js. However, I am unsure about how to connect it when l ...

Trouble arises with kids when trying to adjust the display to block mode

I need to set all the div elements inside the div with id "editor" to display as block. However, when I change the display property of the div with id "editor", only that specific div's display is affected, while everything else inside the div becomes ...

Executing PHP Functions with Script Tags

I am trying to use PHP to output the <script></script> tag. Here is the code I am using: <?php echo "test"; echo "<br>"; echo '<script src="http://mywwebiste./mycode.js" type="text/javascript& ...

My attempts to integrate PHP into jQuery tabs have been unsuccessful

My code seems to be acting strangely, as the PHP code I originally entered in tab 2 has somehow escaped that tab and spread into all the other tabs. This means it is visible in multiple tabs instead of just one. The purpose of this PHP code is to retrieve ...

Resetting the form and validation in AngularJS post form submission

I need help resetting a form and all validation messages after submission. Check out my code on plunker: http://plnkr.co/edit/992RP8gemIjgc3KxzLvQ?p=preview Here is the code snippet: Controller: app.controller('MainCtrl', function($scope) { ...

Obtain the dynamic $scope variable within the HTML structure

When creating numerous directives with dynamic scope variables initialized in the link functions, accessing these values within the directive templates can get tricky. For example: // link: function(scope, ele, attr){ scope.key = scope.somevar + 's ...

CSS responsive design: concealing elements does not prevent the page from being displayed

Imagine a scenario where I need to display a template in two different versions based on the user's device. For instance, I have utilized the following code: <div class="desktop"> <body> Hi Desktop user </body> </div> ...

Having trouble with understanding the usage of "this" in nodejs/js when using it after a callback function within setTimeout

It's quite peculiar. Here is the code snippet that I am having trouble with: var client = { init: function () { this.connect(); return this; }, connect: function () { var clientObj = this; this.socket = ...

Customizing HTML Select Elements

Can the HTML Select attribute be customized to have a flatter appearance? Although I can set the border to be 1px solid, the dropdown part still appears 3D and unattractive. ...

How can I display an image caption within a lightbox using jQuery?

There is a caption under each image. <p> <a href="large.jpg"> <img width="85" height="75" src="thumb.jpg/> </a>Caption</p> I am looking to display the same caption at the bottom of the lightbox. <span id="lightbox-image ...

Encountering error TS2307 while using gulp-typescript with requirejs and configuring multiple path aliases and packages

Currently, I am working on a substantial project that heavily relies on JavaScript. To enhance its functionality, I am considering incorporating TypeScript into the codebase. While things are running smoothly for the most part, I have encountered an issue ...

AJAX File Upload: Sequentially Queuing Multiple Files

I am a beginner in the world of Javascript and jQuery. When I try to upload multiple files through a form, only the last file gets uploaded repeatedly. My goal is to upload each file one by one using AJAX requests asynchronously. Here's how I have ...

How can I generate rotating images using jQuery or JavaScript similar to the one shown here?

http://www.example.com/ On a website similar to example.com, I noticed that when hovering over one of the topics listed, the image rotates. I am interested in creating this interactive effect using either jQuery or JavaScript. Is there a method to access ...

I am in search of a clean and efficient method to modify the class of a link that triggers an HTMX request in Django. Perhaps something like "auto-refresh" or a similar solution would be ideal

I've encountered an issue with HTMX in Django. The page consists of two main components: a list of categories and the content that is displayed when a category is clicked. Initially, everything was working smoothly with standard htmx functionality. H ...