Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataTables: Add class to table cells, but not table headers?

I'm using the following code to initialize jQuery DataTables:

var oTable = $('#qpidvulh_to-do_list').dataTable( {
    "columns": [
        {
            "data": "item",
            "className": "editable"
        }
    ]
} )

The issue with this code is that it adds the editable class to the th of each column, even though I only want it added to the td of each column.

How can I get the code to only add the editable class to the cells of each column and not their headers?

like image 310
eclipsis Avatar asked Nov 07 '14 21:11

eclipsis


3 Answers

Thanks to mainguy and markpsmith for posting their answers. I'll throw my own solution into the mix, but I'd still like to see what everyone thinks the best performing solution would be:

$('#qpidvulh_to-do_list thead th').removeClass('editable');

like image 73
eclipsis Avatar answered Oct 13 '22 22:10

eclipsis


Use this to add the class to the cell, 100% working solution, make sure the you give the correct target number while adding the class, here createdCell function adds class to the targeted cell,

var oTable  = $('#<?php echo $module; ?>').DataTable({
                  columnDefs: [{"orderable": true, "targets": 1,
                        'createdCell':  function (td, cellData, rowData, row, col) {
                           $(td).addClass('myclass');
                           // $(td).parent('tr').attr('data-id', rowData[0]); // adds the data attribute to the parent this cell row
                        }
                  }]
    });
like image 33
Isha Avatar answered Oct 14 '22 00:10

Isha


I had this problem but the suggested solution didn't really work for me because I am applying different types of inputs (number, text) selectively to cells in multiple tables. I have an onclick event for the cell to convert it into an editable box. I changed where it is called from

table.on('click', '.edit-text', function() {
    // yadda yadda;
}

to

table.on('click', 'td.edit-text', function() {
    // yadda yadda;
}

In this way the function ignores the 'th' cells with that class.

EDIT:
A second way I have found is to use the createdCell option in the columns definition:

columns: [
    {
        data: 'property_name',
        createdCell: cell => $(cell).addClass('some-class')
    }
]
like image 23
mark_b Avatar answered Oct 13 '22 22:10

mark_b