Adjust the line selection color in datatables with the power of jQuery

When I click on a row in my datatable, I want the selected row to have a background color of red and all other rows to have a background color of white.

I attempted to achieve this with the following code:

$(document).on('click', "#table_user tr:not(:first) td:first-child", function() {
var row_num = parseInt( $(this).parent().index() )+1; 
 if(row_num == $(this).closest('tr').index()+1){

          $(this).css({'background-color':'red'});
        }else{
          $(this).css({'background-color':'white'});
        }
});

Unfortunately, this code does not seem to work as expected.

Answer №1

If you find yourself in a situation where the if condition will always evaluate to true, consider implementing the following solution:

$(document).on('click', "#table_user tr:not(:first) td:first-child", function() {
  $(this).toggleClass("selected");
});

To style the elements with the .selected class based on their position as even or odd, use this CSS:

.selected:nth-child(even) {
  background-color: #fff;
}
.selected:nth-child(odd) {
  background-color: #f00;
}

Answer №2

To target all rows except the first row specifically, you can use the following code:

$("#table_user td").on('click', function() {
  var row_num = parseInt($(this).parent().index()) + 1;
  var cell_num = parseInt($(this).index()) + 1;
  if (row_num != 1) {
    if(cell_num == 1) {
        $(this).css('background-color', 'red')
  } 
  else {
        $(this).css('background-color', 'white');
  }
 }
});

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

What is causing jQuery toggleClass to fail in removing a class?

I have successfully implemented a Skills accordion feature, but I am now trying to add a button that toggles all the skill sections at once. However, I am facing issues with jQuery not correctly adding or removing classes on the .accordion-trigger-all elem ...

Incorporating jQuery's 'each' method into a JavaScript function

https://i.sstatic.net/CdEkr.pngI'm dealing with a datatable that includes an 'amount' column. I've written a JavaScript function to format the numbers in the table by adding a currency symbol and separating thousands. However, I've ...

Developing Wordpress themes with varying H5 tag sizes across different pages

I'm struggling with a puzzling issue while developing a Wordpress theme. When I zoom in to 250% on mobile, all the header text stays the same size on every page except for one. On that particular page, the text appears significantly larger, almost as ...

Difficulty arises when applying hover effects to animations using callbacks

Currently facing an issue with the hover event in jQuery. There are two side-by-side containers with hover events on both. When hovering, a div containing additional information slides up into view and slides back down when the hover ends. The concept is ...

What are the implications of using :root along with the universal selector in CSS to overwrite Bootstrap variables?

As I work on theming my website, which utilizes Bootstrap, I am making adjustments to the Bootstrap variables. Some variables are defined against the :root element in a way that allows me to easily override them: :root { --bs-body-color: red; } Howeve ...

The Clash of Bootstrap Spanning: Firefox Takes on Chrome and Safari

I am experiencing some strange issues with spacing in different browsers when using Bootstrap. Firefox is showing the spans correctly, but Chrome and Safari are spanning the items across the full width of the page, which I know is a responsive behavior of ...

I am looking to use flexbox and Vue.js to organize my sent messages in blue on the right and received messages in yellow on the left. How can I achieve this grouping effectively?

I've successfully built a messenger system using Vue.js with a Laravel backend. My goal is to display messages from myself (Jim, the logged in user) on the right side in blue and messages from Debbie (the recipient) on the left side in yellow, similar ...

Concealing a div based on a condition

Having difficulty concealing a div once a specific condition is met. The condition depends on the user logging into a web application. In my CSS file, I have set the multipleBox div to visibility: hidden, along with other styling attributes like border co ...

Tips for implementing code to function across several images in HTML and CSS

Hey there, I'm currently working on a website project for my friend and I sometimes refer to www.w3schools.com for help with coding. I'm having trouble implementing a gallery feature where users can click on images to view them fullscreen. I foun ...

Is there a way to keep the header frozen while loading page content during postback?

Currently, I am working with asp.net and c#.net to develop a website. My goal is to create a content navigation system similar to what Microsoft has implemented on their Windows website: Microsoft Windows On this link, users can navigate through page cont ...

The event for changing dates in dangrossman's bootstrap-daterangepicker

Can anyone suggest the best approach for implementing an "on date change" event using the bootstrap-daterangepicker plugin by dangrossman? I need to update in real time, but it seems like there are only options for "on apply" or "on widget hide" events. B ...

Poor response to Ajax request when combined with an else statement

I am currently utilizing Ajax in conjunction with a form to provide user feedback upon submission, indicating whether the process was successful (no errors) or if any input is missing. My approach is quite straightforward as I am using the XMLHttpRequest o ...

What causes child margins to extend beyond the boundaries of div elements?

Can anyone shed some light on the advantages of CSS behavior that allows a child element's top and bottom margins to extend beyond the boundaries of its block-parent? Check out this fiddle for a straightforward example. The pink div is influenced by ...

Is there a way to keep my footer fixed to the bottom of the page in Google Chrome?

I recently made some updates to my aging website by adding a footer menu. However, I encountered an issue with the placement of the footer on Google Chrome. It appears too high, overlapping certain elements of the site. I attempted to resolve this problem ...

Disappearing act: conceal element when overflow is applied to x

While using overflow-y visible on the child div, a 10px section is getting hidden when hovered over. I want that 10px portion of the child to be visible. If I remove both overflow properties, it works fine. What could be causing this issue and how can it ...

Codeigniter displays a view with an empty variable

After submitting data from another form, I am able to successfully retrieve and print the ID with `print($id)`. However, when I try to pass it to the view, the value returned is null. Below is the code snippet: Jquery post function viewAccount(orId) { ...

Choose the final field that is visible when the function is applied

This is the issue I am facing: On our website, we have 5 input fields all sharing the same class name, for example class="inputfield". When the page loads, only the first input field is visible. Next to each field, there is a button that reveals the next ...

Ways to toggle the visibility of an element based on the condition of two other elements

I'm facing a challenging UI use-case that I just can't crack. I have 2 non-nested divs that are causing me trouble (not nesting is crucial here as it would have made things much simpler). Here is the structure of the divs: <div class="a"> ...

Animating scrollTop using JQuery

There are two buttons with hidden parts related to each. When a button is clicked, its associated part will be displayed and the document will scroll to the top. Issue: The displayed part does not move to the top as intended. Your assistance in resolving ...

"My attempts to link various buttons in separate Bootstrap modals to their specific content are not yielding successful results

Greetings fellow members of Stack! Please bear with me as I am a newcomer here. I am currently working on a Business website for a friend using Bootstrap3. On our team page, we have multiple members and I would like to display additional details for each ...