How can I make the row color of a jQuery datatable change when the row is selected?

One of my challenges involves implementing a jquery dataTable (view here) where each row contains a checkbox. I want the row's color to change when the checkbox is checked.

This is the approach I attempted:

<table id="tabellaOrdinaFarmaci" class="table table-striped table-bordered" cellspacing="0" width="100%">
    <thead>
        <tr>
            <th>Codice Farmaco</th>
            <th>Nome Farmaco</th>
            <th>Quantità</th>
            <th>Quantità di alert</th>
            <th>Stato</th>
            <th></th>
       </tr>
   </thead>
   <tbody>
       <?php foreach ($query as $row): ?>
           <tr> 
               <td><?php echo $row->aic; ?></td>
               <td><?php echo $row->denominazione ?></td>
               <td><?php echo $row->quantita; ?></td>
               <td><?php echo $row->alert; ?></td>
                <td><?php echo $row->stato; ?></td>
               <td>  <input type="checkbox" name="radiog_lite" id="<?php echo $row->aic; ?>" class="css-checkbox" />
                  <label for="<?php echo $row->aic; ?>" class="css-label"></label>
               </td>
           </tr>
       <?php endforeach; ?>
   </tbody>

Here's the jQuery code snippet I tried:

jQuery(document).ready(function() {
   jQuery('input').click(function() {
       jQuery(this).parents("tr").css('background-color', 'yellow');
   });
});

The issue I encountered is that this code only colors the rows with odd indices, even though inspecting elements in the browser shows background-color: yellow added to all rows. I suspect the problem lies with Bootstrap dataTable integration. Any assistance would be greatly appreciated. Thank you!

Answer №1

To change the color of a row only when its checkbox is checked, you can utilize the closest() method along with the change event like this:

jQuery('#tabellaOrdinaFarmaci input:checkbox').change(function() {
       if(this.checked)  // check if checkbox is checked then change the row's color
          jQuery(this).closest("tr").css('background-color', 'yellow !important');
    });

Answer №2

When a checkbox in the '#tabellaOrdinaFarmaci' table is changed, this jQuery function will toggle the background color of the corresponding row to yellow.

Translate to AngularJS

Answer №3

Utilize the closest() method in jQuery to locate the parent <tr>

If your elements are added to the DOM at a later time, consider implementing event delegation,

jQuery(document).ready(function() {
    jQuery(document).on('click','input',function() {
        jQuery(this).closest("tr").css('background-color', 'yellow');
    });

});

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

Is it necessary for vertex labels to be distinct within a graph?

I am currently developing a browser-based application that allows users to create graphs, manipulate them, and run algorithms on them. At the moment, each vertex is represented by a unique positive integer. However, I am considering implementing labeled ve ...

Attempting to get Masonry-Layout functioning properly in Safari using imagesLoaded

I recently set up a Masonry Gallery for a WordPress site using Bootstrap 5 with 'Masonry-Layout'. Everything was working perfectly, except in Safari where the layout kept breaking. I know the solution is supposed to be 'imagesLoaded', b ...

The ideal way to efficiently await retrieved data in vue.js to ensure smooth integration in another function

Is there a way to properly handle the successful fetch event before executing the loadMarkers() method? I keep encountering an error because monitorsData.monitors is undefined. I attempted using await with fetch but I'm unsure of the correct usage. ...

Creating a sophisticated form design with multiple input fields using DIV elements in HTML

I am looking to create a multi-column form layout that allows each row to have a different number of fields. My initial approach was using tables and the colspan attribute within td tags for layout structure. However, I have learned that using tables for l ...

What is the best way to verify an array of objects within an asynchronous function?

I am struggling with validating an array of objects being sent to the server. It seems that my current code is not working properly when the array is empty or if the objects within it are invalid. I'm confused about why it's not functioning as ex ...

Encountering a Javascript 404 error while attempting to make an API call

I encountered an issue while trying to modify data in my database. When my api request is made, I am receiving the following error: Uncaught (in promise) SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) Additionally, I am r ...

Tips for utilizing pre-installed validation regulations in VeeValidate 4?

Currently transitioning from Vue 2 to Vue 3, I am interested in utilizing VeeValidate 4 for my validations. However, it seems that the documentation does not provide any information on using built-in rules such as min, max, alpha_spaces, etc. Do I need to ...

Ways to modify the color of every appearance of a term in an html grid using css

My HTML code includes an AngularJS table as shown below: <table id="searchTable"> <thead> <tr> <th>Index</th> <th>Observation</th> <th>Reported By</th> ...

"Refine Your Grid with a Pinterest-Inspired

I've set up a grid of images in columns similar to Pinterest that I would like to filter. The images vary in height but all have the same width. The issue arises when a taller image is followed by a shorter one, causing the short image to float right ...

Unusual occurrences observed with the table

While working with tables, I've noticed an unusual effect. Take a look at the two fiddles below. http://jsfiddle.net/v5co5uy7/ (why are the cells in the left column pushed down?) http://jsfiddle.net/v5co5uy7/1/ (the cells in the left column are posi ...

Utilizing Ternary Operators with User Input

In my latest project, I am developing a cutting-edge app that converts text to sound, utilizing input text from react-native-elements along with ternary operators. My main challenge now is figuring out how to validate whether the text input box is empty ...

Upon loading the page, IE11 activates a CSS transition even when a media query that is not applied is present

Encountering a unique situation with IE11 where a panel (DIV) transition is only activated on pageload if a media query matched the highest CSS specificity for the element. The issue does not occur on Chrome, Firefox, or Safari on tablets and phones. The d ...

The MIME type for .rar and .tar files is not specified

Why is it that Javascript (Windows 8.1, Firefox) doesn't seem to recognize mime types for .tar files or .rar files, among others? Is there a way to fix this issue without resorting to unconventional methods? I really need to be able to get the mime ty ...

Is it possible to convert xaml to html in a silverlight newsletter?

Currently, I am working on a project that involves creating a webpage where my admin can send emails directly through the website. To achieve this functionality, I have implemented a code snippet to send emails to all subscribers. foreach (Subscription pe ...

What causes the unexpected outcome when applying theme overrides in Mui V5?

I am looking to adjust the border radius of all input fields in my project. Specifically, I would like the TextField component to have a border radius of https://i.stack.imgur.com/ULEGj.png instead of https://i.stack.imgur.com/NWmUe.png. According to the M ...

jticker.js enables autoscroll feature on a mobile device

I'm currently utilizing jticker.js to showcase my data. While everything works fine on larger screens, I'm encountering an issue on mobile devices where the scroll stops once the height of the screen is reached. I would like the scroll to contin ...

What is the best way to insert a character (::before) before an element?

I am trying to add a circle/dot using ::before on an element. • • However, I cannot seem to make it visible! .line ::before{ content:'•'; } and .line ::before{ content:'•'; } (Still not showing) I ...

`Combining Promises and yields for seamless functionality`

I have been struggling to incorporate yield with a created Promise. Despite extensively researching, I am still unable to understand where I am going wrong in my implementation. Based on my understanding, when calling the generator function, I need to use ...

Issue with dynamic-rooms causing networked Aframe project to malfunction

I am currently working on a project using A-frame() along with the networked A-frame component: https://www.npmjs.com/package/networked-aframe To view the project, click here: I encountered an issue when attempting to replace the following code in scene. ...

The hovering over a table data element results in a superior transformation

I recently created a table with an interesting structure where the first <tr> contains two <td> elements (the first one having a rowspan), while the second <tr> only has one <td>. My goal is to have hovering over the <td> in t ...