Styling specific header cells in jQuery DataTable with C#CSS, focusing solely on title headers rather than cell data in the columns

Below are the details of my development environment:

- Microsoft Visual Studio Professional 2013

- .NET Framework 4.0

- jQuery-2.1.4.min.js

- jQuery DataTables 1.10.7

- Newtonsoft.Json.7.0.1

- jQuery UI 1.11.2

<table class="table mb-none" id="InfoTable">
                                    <thead>
                                        <tr>
                                            <th><i class="fa fa-street-view     text-muted mr-sm"></i>DRIVER</th>
                                            <th><i class="fa fa-calendar     text-muted space-right"></i>DATE</th>
                                            <th><i class="fa fa-clock-o     text-muted space-right"></i>DUTY CYCLE</th>
                                            <th><i class="fa fa-exclamation-    circle text-muted space-right"></i>VIOLATIONS</th>
                                            <th><i class="fa fa-pencil text-    muted space-right"></i>SIGN</th>
                                            <th class="center"></th>
                                        </tr>
                                    </thead>


                                    <tbody>
                                        <tr class="gradeX">

..............................................
........................................
..............................

We need to apply specific CSS stylings to certain Title Cells of columns.

                var populateInfoTableJS = function () {
                    $('#InfoTable').DataTable({
                        "aoColumns": [
                                        { "sTitle": "LogBsonValueId" },
                                        { "sTitle": "UserID" },
                                        { "sTitle": "DRIVER" },
                                        { "sTitle": "DATE" },
                                        { "sTitle": "DUTY CYCLE" },
                                        { "sTitle": "VIOLATIONS" },
                                        { "sTitle": "SIGN" },

Can someone guide me on how to implement the code so that CSS styling is only applied to specific Title Cells of columns?

Additional question:

                    var populateInfoTableJS = function () {
                        $('#InfoTable').DataTable({
                          "aoColumns": [
                                        { "sTitle": "LogBsonValueId" },
                                        { "sTitle": "UserID" },
                                        { "sTitle": "DRIVER" },
                                        { "sTitle": "DATE" },
                                        { "sTitle": "DUTY CYCLE" },
                                        { "sTitle": "VIOLATIONS" },
                                        { "sTitle": "SIGN" },
                                ],
            "aoColumnDefs": [{ "bVisible": false, "aTargets": [0, 1] }],
            "fnRowCallback": function (nRow, aData, iDisplayIndex) {
                $('tr th:nth-child(1)').addClass('fa fa-street-view text-muted mr-sm');
            },
......................................
................................

I tried the code provided above but it resulted in poor rendering as shown in this image: https://i.sstatic.net/NwlkG.png

Any suggestions on how I can modify the code to improve the appearance of the column headers?

Answer №1

According to Allan, the developer of DataTables, there isn't a direct built-in method for achieving that functionality. You can refer to his response here:

To add classes to cells, you can use a bit of jQuery within the initComplete function or utilize column().header() in conjunction with jQuery.

One way to implement this is by initializing the table:

var table = $('#InfoTable').DataTable({
    // Additional configurations.
});

Then, you can target individual cells using column().header() and apply the class like so:

var header = table.column(0).header();
header.prepend("<i class=\"fa fa-street-view text-muted mr-sm\"></i>");

Keep in mind that the number specified in column(0) represents the column index selector, which can be adjusted accordingly.


Edit

It appears that this line in your code:

$('tr th:nth-child(1)').addClass('fa fa-street-view text-muted mr-sm');

Is adding the classes to the th element instead of i. Refer to this fiddle for clarification. Consider updating it to:

$('tr th:nth-child(1)').prepend('<i class="fa fa-street-view text-muted mr-sm" />');

You can view an example in this fiddle.

Answer №2

Gratitude to @jia-jian for lending a helping hand.

A clever solution was discovered by one of my coworkers:

var populateInfoTableJS = function () {
                    $('#InfoTable').DataTable({
                      "aoColumns": [
                                    { "sTitle": "LogBsonValueId" },
                                    { "sTitle": "UserID" },
                                    { "sTitle": "DRIVER" },
                                    { "sTitle": "DATE" },
                                    { "sTitle": "DUTY CYCLE" },
                                    { "sTitle": "VIOLATIONS" },
                                    { "sTitle": "SIGN" },
                            ],
                       "headerCallback": function (thead, data, start, end, display) {
                        $(thead).find('th').eq(2).html('<i class="fa fa-male text-muted space-right"></i>DRIVER');
                        $(thead).find('th').eq(3).html('<i class="fa fa-sitemap text-muted space-right"></i>DATE');
                    },

It is important to note that there may be complications if you try to hide columns programmatically in the success section when using the AJAX javascript function. For instance, hiding the column with an index value of 2 could cause the DRIVER title to shift to another column occupying the same index value of 2.

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

The Bootstrap datepicker functions properly when used in plain HTML, but encounters issues when implemented within the .html()

Using HTML: <input class="m-ctrl-medium date-picker" size="16" type="text" id='lateETD1' name="dateRecv" value=""/> Not working with script: var ETD = $("#ETD"); ETD.html("<input class='m-ctrl-medium date-picker' id='la ...

Retrieve specifically chosen values from the dropdown menu and eliminate any values that have not been selected

Within my two multiple dropdowns, the first contains all available fields with their corresponding values. The second dropdown displays the selected value along with all other values that were not selected. However, I only want to show the three values tha ...

Issues encountered when dealing with floating elements and margins

Having some difficulties with aligning elements on my website. As someone who is not highly skilled in coding, I am struggling to define the width and float properties for certain classes. Despite my attempts, it seems that the elements are not positioning ...

Run a Python function in Django without any feedback

Currently, I am utilizing Django for a project and I find myself in a situation where I need to carry out certain functions based on user input. If the action requires displaying new values, I know how to handle that. However, when I simply need to execute ...

Vertical positioning offset of jQuery UI selectmenu in relation to buttons on this line

When creating a form, I like to place control elements in a line such as a button, select box, and checkbox for a logical layout. However, after incorporating jQuery UI, I noticed a strange vertical alignment issue with the select box. For reference, here ...

Combining JSF with jQuery for AJAX rendering may necessitate re-binding client-side events in jQuery

Dealing with a recurring issue has led me to a slightly messy solution, prompting me to seek a better approach or a way to prevent the problem altogether. The issue arises when I bind from jQuery to a DOM component and then re-render that component using ...

The Select2 plugin is not retrieving data from the Controller when using DataTables with ajax

I am encountering an issue with Select2 in DataTable as it is not loading. The "GetCompany" method is not being called from the Controller. Can someone please assist me with this? Below is my code snippet: $('#tblQuestion').DataTable({ " ...

Pattern-Based jQuery Selectors

I am looking for a way to use jQuery to select all paragraphs < p > within a < div > that contain time stamps with the following formatting patterns: <p>[22:48]</p> or <p>[22:48 - Subject Line]</p> Can someone provi ...

Unable to retrieve file name with Jquery Ajax and PHP due to error

Trying to display the file name "echo $_FILES['userfile']['name'];" on browser console resulted in "function File() { [native code] }". Below is the jQuery code snippet: <?= form_open_multipart('',' id="importform" m ...

Is there a way to organize an array of elements into three columns using PHP?

My array of menu items is being displayed on the screen in 3 columns, but I want them to appear differently without altering the HTML structure. Currently, they are listed like this: 1 2 3 4 5 6 7 8 9 I would like them to display as follows: 1 4 7 ...

What is the best way to create grid designs using less in bootstrap?

When using Bootstrap without a preprocessor, we include classes directly into our opening tags like this: <div id="El" class="col-md-1"></div> Personally, I usually work with Bourbon Neat and Sass. With Sass, I can import mixins in the rules ...

Expansive Child Division with Ample Margins

I'm currently working with a nested set of divs and I need the inner div to occupy the full width without extending beyond the parent div's margins. Despite trying to use max-width:100%, it hasn't been successful so far. For this particular ...

Accessing web authentication through VBA

Having some difficulties trying to access my webtext account through VBA. The first hurdle I faced was identifying the tags for the username and password input boxes. After using inspect elements, it seems like the tags are "username" and "password." Howe ...

Choose the selectize item to always move to the front

Hey there, I'm currently using the selectize plugin to incorporate tags into my website. Everything is working well, except for the issue of the drop-down item being obscured by some of my other divs. I'm looking to have them function more like ...

Exploring the capabilities of Laravel Webpack Mix and harnessing the power of the

I'm curious about integrating Laravel Webpack Mix with version 5.8 of Laravel. Do I have to include Vue/jQuery in app.js using the extract method in Webpack Mix? Will this result in duplication when loading manifest.js/vendor.js/app.js ? ...

Tips for identifying the clicked location inside an element using JavaScript?

Is there a way in JavaScript to find out the exact position of a click within an element, like its distance from the left, right, or center? I'm struggling to determine whether the clicked area is on the left, center, or right side. https://i.stack.i ...

How can I verify my identity on an external website using jQuery?

I have created a user-friendly login form on my website for easy access. After logging in, users can explore and conduct searches on a 3rd party site that we are partnered with, which provides access to a database resource. The issue lies in the fact that ...

Why isn't the HTML template opening in Outlook 7?

Does anyone know how to fix the code issue on Outlook 7? I've only included the header section of my code here, but please let me know if you need more information. I would appreciate any help with this problem. Thanks! ...

Eliminate any unnecessary or hidden spacing on the left side of the options within an HTML select

Currently, I am in the process of creating a Registration Form and encountering a challenge with aligning the input[type="text"] placeholder and the "pseudo" placeholder for a <select> element. My goal is to have both placeholders left-aligned flush ...

Tips for wrapping text labels in mat-slide-toggles (Angular Material)

Is there a way to get the title in mat-slide-toggle to wrap if it's too long while keeping its default position to the right of the toggle? <mat-slide-toggle class="slider">A really long title wrapped</mat-slide-toggle> I attemp ...