Styling is not being applied to the DataTable when it is invoked through an ajax

I have developed a simple SpringBoot application using Spring Initializer, JPA, embedded Tomcat, Thymeleaf template engine, and packaged it as an executable JAR file. Within this application, I have implemented two datatables: one utilizing ajax and the other without ajax.

<table id="deviceEventTable" class="pure-table"  style="position: relative;">
    <thead>
        <tr>
           <th class="col_battery"><!-- BATTERY -->
                BATTERY
            </th>
            <th class="col_last_event"><!-- LAST EVENT -->
               TIME
            </th>

        </tr>
    </thead>
</table>                            

<table id="deviceEventTable2" class="pure-table"  style="position: relative;">
    <thead>
        <tr>
             <th class="col_battery"><!-- BATTERY -->
                BATTERY
            </th>
            <th class="col_last_event"><!-- LAST EVENT -->
               TIME
            </th>

        </tr>
    </thead>
    <tbody>
        <tr th:each="deviceEvent : ${deviceEvents}"  th:onclick="'window.location.href = \'' + @{/deviceevent/{id}(id=${deviceEvent.id})} + '\''"   >
            <td class="col_battery"><!-- BATTERY -->
                <div class="progressBar" id="max20"><div></div></div><!-- bar % (Change ID maxnumber)-->
            </td>
            <td class="col_last_event"  ></td>
            <!-- LAST EVENT -->
        </tr>
    </tbody>
</table>

When examining the battery column, I observe the following:

<td class="col_battery"><!-- BATTERY -->
                                            <div class="progressBar" id="max20"><div></div></div><!-- bar % (Change ID maxnumber)-->
                                        </td>

Interestingly, on the ajax call, the styling of the elements is not consistent with the expected results as seen in the non-ajax scenario.

https://i.sstatic.net/Oqgf2.png

Below is the usage of the tables:

$(document).ready(function() {

    $.fn.dataTable.ext.errMode = 'throw';

    var ajaxUrl = /*[[@{/api/users/{user}/datatableList(user=${#authentication.principal.id})}]]*/ ""

    var table = $('#deviceEventTable').DataTable( {
        order: [[ 0, "desc" ]],
        select: true,
        bLengthChange: false,
        stateSave: true,
        pageLength: 20,
        ajax: ajaxUrl, 
           "columns": [

               { data: 'battery' },
               { data: 'dateTime' }

           ] 
    });

    setInterval( function () {
        table.ajax.reload( null, false ); 
    }, 2000 );


    table.on('select.dt deselect.dt', function() {
          localStorage.setItem( 'DataTables_selected', table.rows( { selected: true }).toArray() )   
    })




    var table = $('#deviceEventTable2').dataTable( {
        order: [[ 0, "desc" ]],
        select: true,
        bLengthChange: false,
        stateSave: true,
        pageLength: 20,
        initComplete: function() {
            var api = this.api();

            if (localStorage.getItem( 'DataTables_selected' )!=null && localStorage.getItem( 'DataTables_selected' ) != 'undefined') {          
                var selected = localStorage.getItem( 'DataTables_selected' ).split(',');
                selected.forEach(function(s) {
                api.row(s).select();
                })
            }

          } 
    });


} );

/*]]>*/
</script>

To address the issue, I made adjustments to the code:

ajax: ajaxUrl, 
           "columns": [

               { data: 'battery', className: "col_battery" },
               { data: 'dateTime' }

           ] 

The problem seems to be related to another JavaScript function responsible for adding specific classes to elements:

/* 
PROGRESS BAR
*/
// Progress Bar
function progress(percent, element) {
    var progressBarWidth = percent + '%';
        if(percent <= 15){
            element.find('div').addClass("red_bar");
        }else if((percent > 15) && (percent < 50)){
            element.find('div').addClass("orange_bar");
        }else{
            element.find('div').addClass("green_bar");
        }
    element.find('div').animate({ width: progressBarWidth }, 500);
}

$(document).ready(function() { 
    $('.progressBar').each(function() { 
        var bar = $(this);
        var max = $(this).attr('id');
        max = max.substring(3);
        progress(max, bar);
    });
});

Despite attempted fixes, the issue persists.

Answer №1

To customize columns in Datatable Ajax, utilize the columns.createdCell method. Alternatively, if you simply want to assign a class to a column, you can use the className property. Additionally, there is also the option of using createdRow if you need to apply changes to a specific row.

var table = $('#deviceEventTable').DataTable( {
        order: [[ 0, "desc" ]],
        select: true,
        bLengthChange: false,
        stateSave: true,
        pageLength: 20,
        ajax: ajaxUrl, 
           "columns": [

               { 
                 data: 'battery',
                 className: 'col_battery',
                 createdCell: function (td, cellData, rowData, row, col) {
                        //Your JavaScript code here.
                        $(td).css('color', 'red');
                }
               },
               { data: 'dateTime' }
           ],
           createdRow: function (row, data, dataIndex) {
               if (data[4] == "A") {
                  $(row).addClass('important');
               }
           }
    });

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

Every DIV is filled with HTML and CSS

My navigation bar currently has icons placed at the center of a DIV, but I would like to fill up the entire DIV without any spaces left on the sides. The HTML code for the DIV containing the icons is as follows: <nav class="navbar navbar-expand navbar ...

Depressed tomato ( Using the Image .load method with jQuery )

My poor tomato is feeling sad because it's not resizing properly. When I don't include the "load" function, some of my thumbs won't resize, but if I do include it, then the other ones won't resize. startDiv.find('img').each( ...

jQuery is successfully manipulating pagination on CodeIgniter, however, the link is being updated as well

I've been working on a HTML page called view_closing.php. It includes a table with pagination, and my aim is to ensure that the table can move to another record without refreshing the entire page, all while remaining at the same address: http://localh ...

Is there a way to use HTML and CSS to switch the style of a dynamic decimal number to either Roman numerals or Katakana characters within a specified HTML element, such as a tag, div

I've searched everywhere but only found guides on list styling and counter styling in CSS that didn't work out. So, for example, I have a number inside an HTML tag that is changed dynamically using Vue Watch. I want to display the number in upper ...

Ensuring the container height remains consistent with fluctuating content dimensions

Imagine a container with content, where the container's width is fixed but its height adjusts based on its inner content. Initially, when the content causes the container to be a specific height, the challenge arises in shrinking the inner elements w ...

Updating JSF component via AJAX when property value changes

Is it possible to dynamically update a component when a property within the bean is modified? For instance, say I have an ApplicationScoped bean with a List property. I would like for every user to automatically see any changes made to the list without h ...

Utilizing Google Maps autosuggest with JQuery - Trigger load upon selection

Currently, the Google map code operates in the following manner: Upon entering text into the input box, a list of suggestions loads. When you click on one of these options, it places it into the input box. However, you then still need to click "find" to d ...

Tips for appending a custom list item to the bottom of the jQuery autocomplete results

I am using jquery autocomplete and have initialized the following variables $("#some_id").autocomplete("search.php?in=somewhere", { width: 270, selectFirst: false }); $('#some_id').setOptions({max: 5}); The current setup returns ...

Transmission of JSON to a C# controller via AJAX results in a Count value of zero in .NET 7

Whenever I attempt to send a JSON object to my controller, the parameter isn't being received. This is the JavaScript code snippet: var input = document.getElementById("input"); input.addEventListener('change', function () { const read ...

What steps should I take to create a collapsible Bootstrap navbar?

I'm attempting to recreate the scrolling functionality seen here: It seems like they might be using a customized Bootstrap Navbar, so I've taken one from here: and tailored it to my needs. How can I achieve the effect where the navigation bar ...

Can someone explain why my Laravel route is consistently showing a 404 error?

Currently, I am attempting to perform an AJAX request for a form post type. However, the PHP parse script I am trying to send the data to is returning a 404 error as observed through Chrome developer tools. Below is the code snippet: <script type="text ...

Google Maps fails to load when triggered by the jQuery show() function

One issue I'm facing is that the Google Map is not loading after the show() function is called in jQuery. Initially, I use display:none to close a division on page load. After some research, I found out that it can be resolved by using google.maps.eve ...

Why isn't my lightbox able to read this specific property?

A gallery was created using both lightgallery and cycle2. Cycle is a carousel plugin while lightgallery is a lightbox gallery. Clicking on an image in the carousel opens it in the lightbox. Everything worked perfectly until a category in the carousel was ...

What is the best way to ensure the menu background aligns perfectly with the header in HTML/CSS?

Issue: Menu background doesn't align with header. (visible in the image provided below) VIEW IMAGE Any suggestions on how to resolve this alignment problem? CSS CODE : .header { margin:0px auto; max-width: 960px; } #header { height:30 ...

I'm curious about utilizing jsviews in conjunction with jquery sortable

Check out my jsFiddle Example where I am using jsViews in conjunction with JQuery sortable. By default, the remove function works fine; however, when you change the order of items and then try to delete one, multiple items are removed. How can this issue ...

An error occurred with redirecting using jQuery Mobile's new method in version 1.5

Utilizing jQuery Mobile for its history state feature, I am looking to redirect users to another "page" using the jQuery method recommended in their latest documentation. p/s: I prefer the jQuery navigation method due to the hashchange/history support and ...

Should there be an Ajax redirection following creation, or not?

Although I have been successfully using Ajax in a form, I am struggling to determine the best approach for handling actions after a create action. I have implemented respond_with and would like to maintain the same logic in an Ajax call where the create.j ...

How to select the li element in a nested menu using jQuery

My goal is to extract the text from a specific li element when it is clicked on. The code snippet provided below outlines the structure: <div> <ul> <li>list item 1</li> <li>list item 2</li> <li> ...

Sort the null values last when initializing a JQuery DataTable

I am currently working on a webpage that displays data with a date column generated by the application rather than the database. The initial sorting aaSorting is perfect for what I need because users prefer to see the data sorted by this date when they fir ...

Instructions for transferring the model to an ASP.NET controller from a ASP.NET Razor view utilizing jQuery

I've created a Razor view that takes in data. Instead of using the post method directly in the Form, I'm opting to first notify the User about saving. To achieve this, I've set up a save button to trigger a jQuery function which then calls t ...