Toggle the visibility of table rows based on a specific class using a checkbox

I am currently working on a code that displays the results of a query in a table format. I would like to have the ability to click on certain elements to show or hide them. I know this can be achieved using toggle and CSS, but I keep encountering obstacles. Here is a snippet of my code:

The code generates rows for the table based on the query results which are echoed out.

$fields .= "<tr class='viewed' id='".$job_id."' style=".$new_table."><td scope='row' data-label='Date' style='".$new_table."'>".$new_date."</td><td data-label='Pickup'>".$p_city."</td><td data-label='Destination'>".$d_city."</td><td data-label='Pax'>".$pax."</td><td data-label='Vehicle'>".$vehicle_required."</td><td data-label='Status'>".$bidded." (<B>".$bid_count."</B>) </td></td><td width='50px'><button type='button' data-name='".$job_id."' class='btn btn-success'><span class='glyphicon glyphicon-zoom-in'></span> View job </button></td></tr>";

$fields .= "<tr class='unviewed' id='".$job_id."' style=".$new_table."><td scope='row' data-label='Date' style='".$new_table...etc

...

<p>The code I have for implementing checkboxes is as follows:</p>

<pre><code><div class="container">
  <h2>Form control: inline checkbox</h2>
  <p>The form below contains three inline checkboxes:</p>
  <form>
    <label class="checkbox-inline">
      <input type="checkbox" value="">Show viewed
    </label>
    <label class="checkbox-inline">
      <input type="checkbox" value="">Show unviewed
    </label>
    <label class="checkbox-inline">
      <input type="checkbox" value="">Show outofrange
    </label>
  </form>
</div>

In order to toggle the display when clicked, here is the CSS that needs to be toggled:

.viewed {
    display: none;
}

.outofrange {
    display: none;
}

.unviewed {
    display: none;
}

How can I implement a toggle functionality to change between show/hide when clicked?

Thank you

Answer №1

To simplify your click event, you can add the following logic:

$(document).ready(function() {
  $('form input').click(function() {
    if($(this).is(':checked')) {
      $('tr.'+ $(this).attr('id')).show();
    }
    else {
      $('tr.'+ $(this).attr('id')).hide();
    }
  });
});

.snippet-code-css lang-css {
.display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="container">
  <h2>Form control: inline checkbox</h2>
  <p>The form below contains three inline checkboxes:</p>
  <form>
    <label class="checkbox-inline">
      <input type="checkbox" value="" id="viewed">Show viewed
    </label>
    <label class="checkbox-inline">
      <input type="checkbox" value="" id="unviewed">Show unviewed
    </label>
    <label class="checkbox-inline">
      <input type="checkbox" value="" id="outofrange">Show outofrange
    </label>
  </form>
  <div>
  
  <table>
  
  <tr class="viewed">
    <td>viewed</td>
  </tr>
  <tr class="unviewed">
    <td>unviewed</td>
  </tr>
  <tr class="outofrange">
    <td>outofrange</td>
  </tr>
  </table>
  </div>
</div>

Answer №2

To achieve this functionality, you can include the following JavaScript in your webpage. The concept involves attaching click event handlers to each checkbox (input) that triggers specific show/hide actions for three different types of cells: viewed, outofrange, and unviewed:

$(document).ready(function() {

  // Toggle visibility for 'viewed' cell type
  $('form input').eq(0).click(function() {
  
    if($(this).is(':checked')) {
      $('tr.viewed').show();
    }
    else {
      $('tr.viewed').hide();
    }
  })

  // Toggle visibility for 'unviewed' cell type
  $('form input').eq(1).click(function() {
    if($(this).is(':checked')) {
      $('tr.unviewed').show();
    }
    else {
      $('tr.unviewed').hide();
    }
  })

  // Toggle visibility for 'outofrange' cell type
  $('form input').eq(2).click(function() {
    if($(this).is(':checked')) {
      $('tr.outofrange').show();
    }
    else {
      $('tr.outofrange').hide();
    }
  })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="container">
  <h2>Form control: inline checkbox</h2>
  <p>The form below contains three inline checkboxes:</p>
  <form>
    <label class="checkbox-inline">
      <input type="checkbox" value="">Show viewed
    </label>
    <label class="checkbox-inline">
      <input type="checkbox" value="">Show unviewed
    </label>
    <label class="checkbox-inline">
      <input type="checkbox" value="">Show outofrange
    </label>
  </form>
</div>

For a demonstration, check out this live example on jsfiddle

Answer №3

If you want to target specific rows, you can assign a data attribute to each checkbox indicating the class of the row:

<label class="checkbox-inline">
  <input type="checkbox" data-target-class="viewed" value="">Show viewed
</label>
<label class="checkbox-inline">
  <input type="checkbox" data-target-class="unviewed" value="">Show unviewed
</label>
<label class="checkbox-inline">
  <input type="checkbox" data-target-class="outofrange" value="">Show outofrange
</label>

Then, you can utilize this information in your jQuery script like so:

$('form input[type="checkbox"]').on('click', function() {
    var targetClass = $(this).data('target-class');
    var $rows = $('tr.' + targetClass);
    if($(this).is(':checked')) {
        $rows.show();
    } else {
        $rows.hide();
    }
});

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

Unknown individual, yet revealed by the investigator

I'm attempting to develop a dynamic list in react.js generateList = () =>{ return this.state.user.map((u)=>{ console.log(u); return <li onClick={this.handleClick} id={u} name={u}>{u}</li>; }); } The hand ...

Attempting to use tabs within a tab does not function correctly

Visit the CodePen link here This is the codepen example. <div class="row"> <div class="col s12"> <ul class="tabs2"> <li class="tab col s3"><a href="#test1">Test 1</a></li> <li class=" ...

In Firefox, the content within the div element does not respect the maximum width set

My lengthy code won't wrap properly inside the td and div elements. It works fine in Chrome, but Firefox isn't cooperating. Any tips on how to fix this issue? I'm also open to other suggestions for improving my code (e.g. "reduce your use of ...

Error: AppModule requires an array of arguments in order to function properly

Upon successfully compiling my Angular application and running ng serve, I encountered the following error in the browser console. AppComponent_Host.ngfactory.js? [sm]:1 ERROR Error: Arguments array must have arguments. at injectArgs (core.js:1412) at c ...

Issue with overflow:scroll displaying incomplete div contents

I am attempting to create a sidebar with a fixed position, featuring a small header and a scrollable content area below it. The issue I am facing is that I am unable to scroll through the entire content within the div, resulting in some parts being cut of ...

The module 'react/jsx-runtime' could not be located within the path relative to '@mui/styled-engine/StyledEngineProvider/StyledEngineProvider.js'

I encountered this issue when attempting to create a new React project using MUI. I followed this code example from the documentation, which functions correctly in their live Codesandbox but not on my local setup. Here is the complete error message: Module ...

The request's body in the PUT method is void

I seem to be having an issue with my PUT request. While all my other requests are functioning properly, the req.body appears to remain empty, causing this error message to occur: errmsg: "'$set' is empty. You must specify a field like so: ...

Displaying Empty Boxes using Font Awesome

I was able to show Font Awesome properly before, but now it's not working even though I haven't made any changes. I've attempted various solutions but nothing seems to be fixing the issue. My goal is to display it as a placeholder. Below is ...

Could data be transmitted from the server to the client without appearing in network traffic?

I'm in the process of creating a drag-and-drop text game where players have to match correct pairs. Once they've matched all the pairs, they click a button to see how many they got right and wrong. The score is recorded, the boxes reset with new ...

PHP POST data not displaying in output

Having an issue with displaying the chosen value from a database enum in a text field on my website. The enum table has options like Bachelor of Science, Master of Science, Bachelor of Education, and Master of Education. I want to show the selected option ...

Tips for effectively showcasing the counter outcome amidst the increase and decrease buttons

Currently, I am in the process of learning Angular and have created a component called quantity-component. Within the quantity-component.component.html file, I have implemented 2 buttons for increment (denoted by +) and decrement (denoted by -). The decrem ...

What is a way to execute a series of requests using rxjs similar to forkJoin and combineLatest, without needing to wait for all requests to finish before viewing the results?

Consider you have a list of web addresses: urls: string[] You create a set of requests (in this instance, utilizing Angular's HTTPClient.get which gives back an Observable) const requests = urls.map((url, index) => this.http.get<Film>(url) ...

Version 5.0.4 of Mui, when used with makeStyles and withStyles, is experiencing issues with applying styles to Mui

I've been diving into a react project using Mui v5.0.4 and encountered an unexpected issue with my custom styles. Initially, everything was functioning smoothly, but suddenly the styles I had defined were no longer appearing as intended in components ...

Transforming an array of strings into a visual representation

Having an issue parsing a string array for Highcharts consumption. The chart renders when values are static, but not when passed as an array. I have validated the string being parsed here. The main issue appears to be with this specific line: //This work ...

Convert JSON data into the desired format

My JSON input is as follows: [ { "date": { "value": "2022-05-01" }, "parent": { "value": "Choclate" }, ...

Automatically unset session variable 'unsetted' using a simple line of code

Why does the session information not get saved? When I reload the page, the session variable 'mucciusersess' disappears. What could be causing this issue? Thanks... I have a cookie on the client-side with a value like 'mucciuserid' se ...

Unable to alter the default error message within the jquery-validation plugin

I recently came across a post discussing how to change default error messages in jQuery validation. You can check it out here. After reading the post, I decided to modify my js code by adding the following lines to jquer.validate.min.js: jQuery.extend(jQ ...

Iterate through jQuery loop, clear styles, and iterate again

My goal is to animate the "top" position of an HTML element and then reset the style once the function has finished running before starting the loop again. I'm not an expert in this field, and I believe there must be a more efficient way to achieve t ...

Vue does not consistently update HTML when the reference value changes

I am trying to showcase the readyState of a WebSocket connection by utilizing a Ref<number> property within an object and displaying the Ref in a template. The value of the Ref is modified during WebSocket open and close events. However, I am encount ...

develop a submission form using jquery

I am looking to create a submit action where clicking the submit button does not refresh the page. Instead, the data inputted in div1 will be sent to kanjiconverter.php and displayed in div2 using <?php echo $newkanji ?>. There are three forms on thi ...