Unable To Change Background Color Of Selected Row In Datatable Jquery
Solution 1:
You try to change row background color from within rowCallback
which is not supposed to work, since it is triggered before table is rendered.
Instead, you may put 'coloring' code inside row click handler (as suggested here)
Following demo is to illustrate that concept:
const dataSrc = [
{item: 'apple', cat: 'fruit'},
{item: 'pear', cat: 'fruit'},
{item: 'carrot', cat: 'vegie'}
];
const dataTable = $('#mytable').DataTable({
dom: 't',
data: dataSrc,
columns: ['item', 'cat'].map(item => ({title: item, data: item}))
});
$('#mytable').on('click', 'tr', function(){
$(this).toggleClass('selected');
console.log(dataTable.row($(this)).data());
});
.selected {
background: gray !important;
}
tbodytr:not(.selected):hover {
cursor: pointer !important;
background: lightgray !important;
}
<!doctype html><html><head><scripttype="application/javascript"src="https://code.jquery.com/jquery-3.3.1.min.js"></script><scripttype="application/javascript"src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script><linktype="text/css"href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css"></head><body><tableid="mytable"></table></body></html>
Above code presumes that you're not using 'select' extension for DataTable
If above selection is required to be persistent (upon table re-draw, e.g. triggered by AJAX-call), there can be introduced an array that stores id's of table records (e.g. const selectedRowIds = []
within global scope), and createdRow
option can be employed in order to re-apply class selected
upon re-draw if row id is found within selectedRowIds
:
const dataTable = $("#mytable").DataTable({
...
createdRow: (row, data, dataIndex, cells) => {
if (selectedRowIds.indexOf(data.id) > -1)
$(row).addClass("selected");
}
});
Also, row click handler should be extended with the logic that will append/remove selected row id into/from selectedRowIds
:
$("#mytable").on("click", "td", function () {
//get clicked table row nodeconst clickedRow = dataTable.row($(this).closest("tr"));
//append/remove selected row 'id' property value to global array
selectedRowIds = $(clickedRow.node()).hasClass("selected")
? selectedRowIds.filter(rowId => rowId != clickedRow.data().id)
: [...selectedRowIds, clickedRow.data().id];
//toggle class 'selected' upon clicking the row
$(clickedRow.node()).toggleClass("selected");
});
You may find the complete demo over here or inspect that with your browser's Dev Tools, using this link.
Solution 2:
Try changing background color of td tags of row.
$('td', row).css('background-color', 'orange');
Post a Comment for "Unable To Change Background Color Of Selected Row In Datatable Jquery"