Datatables jQuery provides the ability to dynamically assign array index values to the 'sClass' property

Consider this code snippet:

let dataSet = [
    ['1', 'Safari','Mac OS X','13.1','A','N/A'],
    ['2', 'Chrome','Windows 10','90','B','N/A'],
    ['3', 'Firefox','Ubuntu','88','A','N/A']
];

$('#example').dataTable( {
    "aaData": dataSet,
    "aoColumns": [
        { "sTitle": "Browser" },
        { "sTitle": "Operating System" },
        { "sTitle": "Version", "sClass": "customCSS-" + dataSet['id']['Version'] }, 
        { "sTitle": "Grade", "sClass": "center" }
    ]
} );    

I want to retrieve the Version information of the current dataSet element being processed, and use it for string concatenation within the aoColumns styling. The styling seems to not work properly as of now. By changing the line to:

    { "sTitle": "Version", "sClass": "customCSS-" + dataSet[0]['Version'] }

it correctly styles all elements based on the first index, but I am trying to figure out how to perform a dynamic lookup. Any help on this issue would be greatly appreciated.

Answer №1

It seems that the concern lies with the Version value, which contains dots and may disrupt the CSS styling. To address this, I have excluded the Version value from the concatenation of the css class name. If the goal is understood correctly, the task can be achieved using the method demonstrated on jsbin:

http://jsbin.com/onelev/2/edit

The key approach here is utilizing fnRowCallback to generate the dynamic class name on the table cell.

CSS for designing custom cell colors

.customCSS-Trident, table.dataTable tr.even td.customCSS-Trident.sorting_1, table.dataTable tr.odd td.customCSS-Trident.sorting_1 { background-color: blue; color: #fff; }
.customCSS-Fish, table.dataTable tr.even td.customCSS-Fish.sorting_1, table.dataTable tr.odd td.customCSS-Fish.sorting_1 { background-color: green; color: #fff; }
.customCSS-Pony, table.dataTable tr.even td.customCSS-Pony.sorting_1, table.dataTable tr.odd td.customCSS-Pony.sorting_1 { background-color: brown; color: yellow; }
.customCSS-Cabbage, table.dataTable tr.even td.customCSS-Cabbage.sorting_1, table.dataTable tr.odd td.customCSS-Cabbage.sorting_1 { background-color: pink; }

JavaScript

$(document).ready( function() {
  var oTable = $('#example').dataTable( {
    "aaData": aDataSet,
    "aoColumnDefs": [ 
      {  "aTargets": [ 0 ], 
         "sTitle": "#" 
      },
      {  "aTargets": [ 1 ], 
         "sTitle": "Engine" 
      },
     { "aTargets": [ 2 ], 
        "sTitle": "Browser" 
     },
     { "aTargets": [ 3 ], 
      "sTitle": "Platform" 
     },
      { "aTargets": [ 4 ],
       "sTitle": "Version"
     },      
     { "aTargets": [ 5 ], 
       "sTitle": "Grade", 
       "sClass": "center" 
      }
    ], 
     "fnRowCallback": function( nRow, aData, iDisplayIndex ) {
       $('td:eq(4)', nRow).addClass("customCSS-" + aData[1]);    
         return nRow;
     },
  });
} );

HTML

<table cellpadding="0" cellspacing="0" border="0" class="display" id="example">
  <thead>
    <tr>
      <th>#</th>
      <th>Engine</th>
      <th>Browser</th>
      <th>Platform(s)</th>
      <th>Engine version</th>
      <th>CSS grade</th>
    </tr>
  </thead>
  <tbody>
  </tbody>
</table>

Addendum
DataTables automatically generates the sorting_1 class when a column is sorted. If users click multiple column headers while holding the shift key, additional classes like sorting_2 are created. Although this scenario may be rare, you can account for it by adding extra css rules for those cases.

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

Superimpose above the tbody

I am attempting to implement a loading overlay specifically on top of the tbody element. My current method involves adding a tr as the last child of tbody and positioning it using position: absolute, while setting the parent tbody with position: relative. ...

Always ensure that the horizontal scrollbar is visible without the need for vertical scrolling

I'm attempting to create a data grid-style layout where the left side is fixed and only the right side is scrollable. However, the entire div needs to be vertically scrollable. The concept is functioning correctly, but the horizontal scrollbar appears ...

splitting lengthy words into several lines

Does anyone know how to break words like the examples below using CSS or jQuery? SAMPLE 1 ConfigTechnologyHormonyAppComponentBackOfficeLaunch It needs to be broken into ConfigTechnologyHo rmonyAppComponentB ackOfficeLaunch SAMPLE 2 WorkAppComponentBa ...

Utilize jQuery's addClass Method when Submitting a Form Using Ajax

When the form is submitted, I would like to add a class and display a loading animation before executing the AJAX request. However, when setting async to false in the AJAX call, the AJAX request will be executed first before displaying the loading animatio ...

Here is how to display a text box instead of a dropdown select box when receiving a null value from a JSON response

When retrieving JSON data from the controller to display in a dropdown select box, I encountered an issue. If the JSON data is null, I want to display a text box instead of the dropdown to manually input the data. public function getyear(Request $requ ...

Guide to dynamically displaying different URLs based on checkbox selection using Ajax

My goal is to dynamically change the view of a page based on which checkbox is checked. Additionally, I want to ensure that when one checkbox is selected, another becomes unchecked. <input class="searchType" type="checkbox"></input> <input ...

Concentrate on all elements within the form

I am in the process of developing a form with multiple input fields, one of which is shown below. I am interested in triggering an event using jQuery's focusout function. The form goes by the name: form_test <form id="form_test"> <input ...

Creating CSS styles for mobile devices, such as smartphones and tablets

Hey there! I've been using CSS for developing desktop websites for quite some time now, and I'm eager to expand my skills to build websites that cater to a variety of devices like phones, smartphones, tablets, and even consoles with web browsers. ...

The console is throwing an error indicating that the function $(...).tooltip is not recognized

I keep encountering an issue where the console displays an error message stating that $(...).tooltip is not a function. Below is the code snippet causing the error: $('.selector').tooltip().mouseover(test); ...

Show Navbar Toggler only when in Portrait mode on mobile devices, not Landscape mode

Attempting to create a responsive website utilizing Bootstrap 4, I encountered a problem with the menu expanding in Landscape orientation on mobile devices, causing distortion. How can I ensure the menu stays collapsed in Landscape orientation? Despite ha ...

Removing CSS from a button inside a jQuery Mobile popup: a step-by-step guide

Within a jQM dialog, I have a pair of buttons: <a href="#" data-role="button" data-inline="true">Yes</a><a href="#" data-role="button" data-inline="true" data-rel="back">No</a> These buttons are automatically styled by jQM, incorp ...

Having trouble with jQuery AJAX - page continually refreshes upon submitting and data isn't being transmitted

I've been working on creating a dynamic AJAX function using PHP and MySQL to update database records without the need for page refresh or navigation. However, I haven't had much success with it yet. Here's the code I have on the page with t ...

When arranging elements using the @media feature in CSS grid, a phantom element seems to mysteriously appear

Apologies for the extensive uploads, I'm not sure how else to proceed. I'm attempting to rearrange my grid layout at a specific width so that the paragraphs repeat with the images. However, I'm encountering a random space between 1 and 2 whe ...

Steps to manage the time delay between mousewheel events triggering

Currently, I am working on a website for a movie production company that showcases their various films in full-screen mode. Each video is listed and there is a function that automatically takes the user to the next video when a mousewheel event occurs. How ...

Move the DIV element to the bottom of the webpage

On my website, I have implemented a countdown timer and a responsive wallpaper. My goal now is to center the div at the bottom of the page and make sure it always stays there. I've tried some code snippets from StackOverflow, but they either gave me a ...

combining the name of an array with a numeric value

I have several arrays, named array_1, array_2 through array_5. Based on a specific level, I aim to utilize an array. For instance, when level = 1, I want to use array_1. Attempting myArr = array_ + level results in myArr not being recognized as an array ( ...

What is the best way to print a canvas element once it has been modified?

My goal is to include a "Print Content" button on a webpage that will print a canvas element displaying workout metrics. However, the canvas content, which consists of a visual graph of workout data, changes based on the selected workout (bench, squat, etc ...

Stop ajax loading animation for a specific scenario

I usually have a global ajax load animation that runs during every ajax call. However, there are certain cases where I need to disable this effect. How can I achieve that? This is the code for the global animation : $(document).ajaxStart(function(){ $ ...

"Discover a simple method to calculate the combined value of checkboxes and seamlessly transfer it to the next page

I have utilized jQuery to perform calculations on Page1.html, where I retrieve values from input boxes using the get function and set those values in other input boxes using the set function. I am having trouble getting the total value of checkboxes when t ...

Managing project versions and branches with gulp as the source control system

As a beginner in node.js and gulp, I apologize for the simplicity of my question. I am embarking on a new jQuery project using node.js and gulp. Below is the structure of my directory and files: /root-pluign-directory | ---- dist (holds release f ...