Using jQuery to dynamically update the CSS of one table column depending on the attribute of another column

Welcome to my HTML table

<!DOCTYPE html>
<html>
<body>
<table>
<thead>
<th>Title1</th>
<th>Title2</th>
</thead>
<tbody>
<tr>
<td><input type="checkbox" id=0 /></td>
<td>TEXT99</td>
</tr>
<tr>
<td><input type="checkbox" id=1 checked/></td>
<td>TEXT100</td>
</tr>
</tbody>
</table>

</body>
</html>

tap here for more details

My task is to parse all the rows in the table (after the page loads) and change the styling of the second column's text using jquery (as shown in the link)

For example, the table above should appear like so (with TEXTUSD crossed out)

I think we can adjust the css of an element with jquery's css method as follows

.css("text-decoration", "line-through")

However, I am unsure how to create a jquery code snippet that can loop through all the rows in the table and modify the css.

Do you think this is achievable with jquery?

Any assistance would be greatly valued !!!

Answer №1

1. Starting the setup

If you want your script to execute after the page has loaded, you can use the .on() method with the load event.

Ref: .on() | jQuery API Documentation

2. Looping through specified elements:

To iterate over specific elements, you can utilize the .each() method along with certain CSS selectors like td > input, focusing directly on nested input elements within td elements (avoiding all nested input targeting and eliminating the need for an additional .find() method).

Ref: .each() | jQuery API Documentation

3. Validating the necessary condition:

To confirm if a particular element possesses the checked attribute, use a conditional statement such as if() to assess if the condition is true.
If it satisfies the condition, apply the required inline style using the .css() method inside the conditional block.

Ref: .css() | jQuery API Documentation

Code Illustration:

$(window).on('load', function(){
  
  $('td > input').each(function(){
    if($(this).attr('checked')) {
      $(this).parent().next().css('text-decoration', 'line-through');
    }
  });
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <thead>
    <th>Header1</th>
    <th>Header2</th>
  </thead>
  <tbody>
    <tr>
      <td><input type="checkbox" id="text0" /></td>
      <td>TEXT1</td>
    </tr>
    <tr>
      <td><input type="checkbox" id="text1" checked/></td>
      <td>TEXT2</td>
    </tr>
  </tbody>
</table>

Note:

  1. id selectors are not valid if they start with a number (number/unit value), e.g: id="0", it must commence with a string, e.g: id="text0"
  2. Enclose attribute values in quotation marks, e.g: id="text0"

Answer №2

I have implemented this functionality using jQuery:

The goal is to strike out the text in the second column when the checkbox next to it is checked. Additionally, the text should be struck out if the checkbox is clicked by the user.

$(document).ready(function(){
 $('input:checkbox').on('change', function () {
        var td = $(this).parent().next('td');
        if (this.checked) {
           
            $(td).css('textDecoration', 'line-through');
        } else {
            $(td).css('textDecoration', 'none');
        }
    });
  var tdChecked = $('input[type=checkbox]:checked').parent().next('td');
  if ($('input[type=checkbox]:checked')) {
           
            $(tdChecked).css('textDecoration', 'line-through');
            }
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
<table>
<thead>
<th>Header1</th>
<th>Header2</th>
</thead>
<tbody>
<tr>
<td><input type="checkbox" id=0 /></td>
<td>TEXT1</td>
</tr>
<tr>
<td><input type="checkbox" id=1 checked/></td>
<td>TEXT2</td>
</tr>
</tbody>
</table>

</body>
</html>

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

Utilizing AngularJS routes to load a specific URL when accessing a page for the first time

Working on developing a Single Page Application using AngularJS, my configuration settings appear as follows: app.config(["$routeProvider", function($routeProvider) { return $routeProvider .when("/", { redirectTo: " ...

Is it possible to use a Jasmine spy on a fresh instance?

In need of assistance with testing a TypeScript method (eventually testing the actual JavaScript) that I'm having trouble with. The method is quite straightforward: private static myMethod(foo: IFoo): void { let anInterestingThing = new Interesti ...

Having trouble viewing the header in devtools for $http requests?

The data in the request header is not visible to me. Here's what I'm using: $http.post('http://localhost/api/validate', {}, { headers: key } ); https://i.sstatic.net/yioTT.png The form that gets passed during runtime is shown below: ...

How can I set a dropdown back to the first index in MVC?

Within my MVC project, I have a dropdown list bound in a div using the code snippet below: @{ List<SelectListItem> lsqty = new List<SelectListItem>(); for (int i = 1; i <= 10; i++) { SelectListItem sl = new SelectListIt ...

The Bootstrap Grid Leaves Blank Spaces Unfilled

View the screenshot here Take a look at the image above. I'm struggling to fill the empty space with div elements. I've experimented with display:inline-block and other display properties, but they haven't yielded the desired results. < ...

Having trouble with Mongoose's findOne method not functioning as expected

I am developing an application where users can input data such as the number of hours they slept and their eating habits. This information is then stored in a collection known as the Journal. When a user clicks on "stats", it activates a function called f ...

Implementing CSS Media Print, tables elegantly transition to a fresh page

I am encountering a challenge when it comes to printing my dynamic table along with some preceding text. It seems that sometimes the table begins on a new page, resulting in the header test being isolated on the first page and only displaying the table on ...

Taking out the z-index from the transition code

Is there a way to restructure the code without needing to use z-index for the transition? Without z-index: https://jsfiddle.net/Legcb42d/ .container1 { position: relative; width: 100%; height: 100%; } .container1.slide { height: auto; min-heigh ...

Connecting the mat-progress bar to a specific project ID in a mat-table

In my Job Execution screen, there is a list of Jobs along with their status displayed. I am looking to implement an Indeterminate mat-progress bar that will be visible when a Job is executing, and it should disappear once the job status changes to stop or ...

Tips for removing an element from an array in a JSON structure using its unique identifier

This problem seems to be fairly straightforward but it’s giving me some trouble. Here is the JSON structure I'm working with: "playlists" : [ { "id" : "1", "owner_id" : "2", ...

Sequentially iterate through elements based on their Data attributes

Assume you are working with HTML elements like the ones shown below <span class="active" data-id="3"> Test 3 </span> <span class="active" data-id="1"> Test 1 </span> <span class="activ ...

Struggling with a CSS problem that jQuery can't seem

I recently experimented with Infogrid on my website. After adding a header and footer, I noticed that the text in the last block of iron man was being cut off. Even though I removed overflow:hidden; from the body and html, the issue persisted with the te ...

Are you in favor of side-to-side scrolling?

I can't quite recall where I've encountered this concept before, but I do know that there must be a method for creating a horizontal scroll. Imagine you have multiple DIVs in the following structure: <div class="container"> <div> ...

Is there a method available to selectively `cache` specific tabs?

Is there a way to selectively cache tabs in jQuery-UI? For example, I have 3 tabs and I only want to cache tab number 2. I am aware that we can use the following code: $( ".selector" ).tabs({ cache: true }); However, this caches all tabs, not just the ...

Manipulating AngularJS with Sass variables

Currently, I am developing a theme changer using AngularJS and I'm facing difficulty in figuring out how to swap one SASS file with another (both containing variables) when the user changes their theme. I understand that once SASS is compiled to CSS, ...

One approach could be utilizing either JavaScript object notation or jQuery code to establish class properties that are also classes in their own

Here is an example of what I currently have: var Class1=function(p1,p2){ //constructor code } Class1.prototype={ method:function(){...}, method:function(){...} } I am looking to make Class2 a part of Class1 so that I can do the following: inst ...

Accordion featuring collapsible sections

Looking to build an accordion box using Javascript and CSS. The expanded section should have a clickable link that allows it to expand even further without any need for a vertical scroll bar. Any ideas on how this can be achieved? Thank you ...

The values of nested objects are not being passed as parameters from the AJAX call to the action method

How can I ensure that the nested object values in the parameter are passed correctly to the action method in the controller along with the full object? When calling the AJAX method, the values in the object inside the red ring on the pictures do not get p ...

Tips for enhancing the fluidity of animations after removing an item from a list

I'm working on a project where I have a list of elements that are removed with an animation when clicked. However, I noticed that when one element is removed, the rest of the elements just jump up instead of smoothly transitioning. Is there a way to m ...

Selecting a specific section from a JSON data reception

Upon executing a POST request to , the resulting response typically looks like this: { "success": true, "data": { "url": "http://i.imgflip.com/1nciey.jpg", "page_url": "https://imgflip.com/i/1nciey" } } Is there a way for me to output the s ...