Toggle the display of selected options based on the presence of multiple classes within a td element

Upon selecting an option from a dropdown, certain columns are shown while others are hidden. Some columns have multiple classes assigned to them.

For instance:

"object 7" belongs to "category 1" and "category 3".

"object 7" is visible in "category 3" but not in "category 1".

I wish to also display it in category 1.

function categories() {
  var sections = document.getElementById("sections").value;

  if (sections == "cat1") {
    $('.cat1').each(function() {
      this.style.display = "table-cell"
    });
  } else {
    $('.cat1').each(function() {
      this.style.display = "none"
    });
  }
  if (sections == "cat2") {
    $('.cat2').each(function() {
      this.style.display = "table-cell"
    });
  } else {
    $('.cat2').each(function() {
      this.style.display = "none"
    });
  }
  if (sections == "cat3") {
    $('.cat3').each(function() {
      this.style.display = "table-cell"
    });
  } else {
    $('.cat3').each(function() {
      this.style.display = "none"
    });
  }
  if (sections == "tous") {
    $('.cat1, .cat2, .cat3').each(function() {
      this.style.display = "table-cell"
    });
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div><select class="form-control" id="sections" name="sections" onchange="categories()">
      <option value="choose" selected disabled>Choose</option>
      <option id="cat1" value="cat1">category 1</option>
      <option id="cat2" value="cat2">category 2</option>
      <option id="cat3" value="cat3">category 3</option>
      <option id="all" value="all">All</option>
    </select>
</div>

<table class="table table-striped">
  <thead>
    <tr>
      <th class="cat1">item 1</th>
      <th class="cat1">item 2</th>
      <th class="cat2">item 3</th>
      <th class="cat2">item 4</th>
      <th class="cat3">item 5</th>
      <th class="cat3">item 6</th>
      <th class="cat1 cat3">item 7</th>
      <th class="cat2 cat3">item 8</th>
    </thead>
      <tbody class="text-primary">
      <tr>
      <td class="cat1">item 1</td>
      <td class="cat1">item 2</td>
      <td class="cat2">item 3</td>
      <td class="cat2">item 4</td>
      <td class="cat3">item 5</td>
      <td class="cat3">item 6</td>
      <td class="cat1 cat3">item 7</td>
      <td class="cat2 cat3">item 8</td>
      </tr>
    </tbody>
  </table>

Please point out any issues you see in my code.

Answer ā„–1

If you want to simplify your code, consider the following approach:

var sections = document.getElementById("sections").value;
$('table tr td').each(function(){
   $(this).css('display', $(this).hasClass(sections) ? 'block' : 'none');
});

The display property needs to be changed based on a condition.

$(this).hasClass(sections)

The hasClass method checks if any matched elements have the specified class.

function categories() {
  var sections = document.getElementById("sections").value;
  $('table tr td, table tr th').each(function(){
    $(this).css('display', $(this).hasClass(sections) ? 'inline-block' : 'none');
  });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div><select class="form-control" id="sections" name="sections" onchange="categories()">
      <option value="choose" selected disabled>Choose</option>
      <option id="cat1" value="cat1">Category 1</option>
      <option id="cat2" value="cat2">Category 2</option>
      <option id="cat3" value="cat3">Category 3</option>
      <option id="all" value="all">All</option>
    </select>
</div>

<table class="table table-striped">
  <thead>
    <tr>
      <th class="cat1">item 1</th>
      <th class="cat1">item 2</th>
      <th class="cat2">item 3</th>
      <th class="cat2">item 4</th>
      <th class="cat3">item 5</th>
      <th class="cat3">item 6</th>
      <th class="cat1 cat3">item 7</th>
      <th class="cat2 cat3">item 8</th>
    </thead>
      <tbody class="text-primary">
      <tr>
      <td class="cat1">item 1</td>
      <td class="cat1">item 2</td>
      <td class="cat2">item 3</td>
      <td class="cat2">item 4</td>
      <td class="cat3">item 5</td>
      <td class="cat3">item 6</td>
      <td class="cat1 cat3">item 7</td>
      <td class="cat2 cat3">item 8</td>
      </tr>
    </tbody>
  </table>

Answer ā„–2

To start off, it is recommended to use jQuery to attach the change event.

$('#sections').on('change', function(){
    //Your event logic goes here
});

Next, remove the inline onclick from your select:

<select class="form-control" id="sections" name="sections">

You can hide all the td and th elements after every change, then show them by classname like so:

$('.'+class_name).show();

I hope this solution proves helpful for you.

$('#sections').on('change', function(){
   var class_name = $(this).val();
   
   $('td,th').hide();
   $('.'+class_name).show();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div><select class="form-control" id="sections" name="sections">
  <option value="choisir" selected disabled>Choose</option>
  <option id="cat1" value="cat1">Category 1</option>
  <option id="cat2" value="cat2">Category 2</option>
  <option id="cat3" value="cat3">Category 3</option>
  <option id="all" value="all">All</option>
  </select>
</div>

<table class="table table-striped">
  <thead>
    <tr>
      <th class="cat1">item 1</th>
      <th class="cat1">item 2</th>
      <th class="cat2">item 3</th>
      <th class="cat2">item 4</th>
      <th class="cat3">item 5</th>
      <th class="cat3">item 6</th>
      <th class="cat1 cat3">item 7</th>
      <th class="cat2 cat3">item 8</th>
  </thead>
  <tbody class="text-primary">
    <tr>
      <td class="cat1">item 1</td>
      <td class="cat1">item 2</td>
      <td class="cat2">item 3</td>
      <td class="cat2">item 4</td>
      <td class="cat3">item 5</td>
      <td class="cat3">item 6</td>
      <td class="cat1 cat3">item 7</td>
      <td class="cat2 cat3">item 8</td>
    </tr>
  </tbody>
</table>

Answer ā„–3

After making a tweak to your code, now it hides all elements at first and then displays each class one by one

    function categories() {
        var sections = document.getElementById("sections").value;

        // hide all elements initially
          $('.cat1, .cat2, .cat3').each(function() {
            this.style.display = "none";
          });            



        if (sections == "cat1") {
          $('.cat1').each(function() {
            this.style.display = "table-cell";
          });
        } 
        if (sections == "cat2") {
          $('.cat2').each(function() {
            this.style.display = "table-cell";
          });
        } 
        if (sections == "cat3") {
          $('.cat3').each(function() {
            this.style.display = "table-cell";
          });
        }
        if (sections == "all") {
          $('.cat1, .cat2, .cat3').each(function() {
            this.style.display = "table-cell";
          });
        }


      }

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

Edge and Internet Explorer fail to recognize the :focus CSS selector

I am utilizing CSS to make our placeholders jump up when clicked inside, but Edge is not recognizing the CSS. It works fine on every other browser except for Edge. I've tried various solutions but none seem to work on Edge. Any thoughts on what might ...

Add a plugin to the website after the DOM has finished loading

Here is a code snippet that utilizes a jQuery plugin to apply scrollbars to a DOM element: <script type="text/javascript"> $(document).ready(function () { $(".pp-meta-content").customScrollbar(); }); </script> This code works ...

Using Jstree checkboxes to trigger an Ajax call and send the checked data to a controller in Codeigniter

When using JStree checkbox in codeigniter, I was able to display the checkbox jstree using the code below: <script> $("#newtree").jstree({ "checkbox" : { "keep_selected_style" : false }, "plugins" : [ "check ...

When using React.js with Leaflet, ensure that the useEffect hook is only run on Mount when in the

I have encountered an issue where I need to ensure that the useEffect Hook in React runs only once. This is mainly because I am initializing a leaflet.js map that should not be initialized more than once. However, anytime I make changes to the component&a ...

Can you apply Bootstrap 5 custom color directly to the class attribute?

just like this: <span class="text-primary">some text</span> I'm curious if there's a way to achieve the following: <span class="text-red-300">some text</span> The red-300 color in Bootstrap 5 is a c ...

Implementing dynamic CSS class addition on CodeIgniter web pages

Exploring the templating mechanism I use in my CodeIgniter application: public function index($page = 'login') { $this->load->view('admin/header',array('page'=>$page)); $this->load->view(&a ...

The options in the dropdown menu vanish when interacting with a jQuery feature that relies on

Recently, I have found AJAX, JSON, and jQuery to be indispensable tools in my coding endeavors. The application I am working on is a replacement for a flawed one, and it is coming along nicely. Despite making progress with the AJAX method, I have encounte ...

What is the purpose of using a hash in a WebSocket handshake?

When establishing a Websocket connection, the client initiates by connecting to a tcp socket on a server and then performs a handshake. In the client's handshake, there is a base64 encoded key (Sec-WebScoket-Key). The expected response from the serv ...

Increase the font size of a div using CSS to make it appear larger

Utilizing a WYSIWYG-editor, I am creating content that I want to display with double font-size, without directly altering the HTML code. Here is an example of the HTML structure: <div id="contents"> <p style="text-align:center"> <spa ...

Failing to include a valid string in the path will result in an

Within my node API, I have a function that updates the email address array for either a contact or a farm. The concept is the same, but the difference lies in where the array is located: in farms it's within Records.emails, and in Contacts it's s ...

Is it necessary to use a specific button to submit on Return (Enter)?

In a wizard-type form, there are two buttons present. The Back button is positioned on the left side, while the Next button is located on the right side. For an example of this setup, visit http://jsfiddle.net/WSwb7/1/. Please note that submitting the form ...

What could be causing an error to be thrown when I call the destroy function for my waypoints

After experimenting with waypoints.js (jQuery version), I decided to share my progress so far. If you want to take a look, click here. In my current setup, the 'destroy' function for waypoints has this code snippet attached: $('.destroy&ap ...

What does the client perceive or not perceive? Node.js, JavaScript, MySQL

For a university project, I am tasked with creating a web application that is compatible with both desktop browsers and mobile devices. The technologies I will be using include HTML, CSS, JavaScript, Node.js, and MySQL. I have recently familiarized myself ...

Ways to direct to a specific div upon clicking an anchor tag following a page reload?

<a href="#goto">Link 1</a> <div id="goto">DIV</div> Whenever I click on the anchor tag, my webpage reloads and displays a new div with the ID of goto. This div was previously hidden but is now visible at the bottom of the page. I ...

"When I use breakpoints and run my application in debugging mode, it performs flawlessly. However, without these tools, it

I have developed an application using the Ionic Framework with Firebase as the backend. When I run the application with breakpoints using the debugger, everything works fine. However, if I run it without the debugger, I notice that values are not being upd ...

How can I modify the style of a cell in jqgrid when the mouse hovers over it?

I need to change the class of cells in the first column of my grid. Currently, I set them using this code: $("#myGrid").jqGrid('setCell',rowid,'column_1', '', '**ui-state-default**'); Is there a way to modify the c ...

What is the best way to incorporate link tags into text in AngularJS?

I'm struggling with making links within strings clickable in Angular. Can anyone provide guidance on how to accomplish this? One of the string examples from my JSON data is: "Iā€™m hosting #AFF Catwalk Show @Bullring on 27th Sept with @BillieFaiers. ...

The onload function on the iframe is triggering twice in Internet Explorer 11

I am encountering a strange issue with an iframe in HTML that has an onload function. When using IE11, the onload function is being triggered twice, whereas it works fine in Chrome. Here is the HTML code: <iframe src="someurl" onload="someFunction( ...

Transmit data in the form of a buffer

const response = await client.render(data); const Writable = require('stream').Writable; var buffer = []; const myWritableStream = new Writable({ write(chunk, encoding, callback) { ...

Is it possible in Jquery Keyboard to automatically synchronize the value I am typing with the input field?

I have integrated the jquery keyboard plugin into my project. Currently, when a user clicks on an input (A), the keyboard appears at the bottom of the page showing input (B) as well. As the user types, only the value of input (B) changes on the keyboard, ...