compare two columns using datatables - javascript

My goal is to highlight a row if two columns contain the same string within a row using datatables
I am not sure how would I compare two columns. I want to do something like this.
This is part of my code
"columnDefs":[
{
"targets":[3,4],
"render": function ( data, type, full, meta ) {
if value of 3 = 4 {
//highlight the row
}
}
} ],
Thanks in advance.

SOLUTION
Use rowCallback option to define a callback function that will be called when row would be drawn.
$('#example').dataTable({
"rowCallback": function(row, data, index){
if (data[3] === data[4]) {
$(row).addClass('selected');
}
}
});
DEMO
See this jsFiddle for code and demonstration.

Related

How to add rows when exporting data into excel in Datatable?

I try to export my datatable into Excel.
Every time when exporting the table I want to add 3 default rows at the very top.
I saw a datatable message option but that might not help me because I want 3 rows.
Actual
Now I have this data (without any extra rows):
Expected
But I want to export data with these extra rows :
I have this code right now. and i have tried adding header with message but that didn't work for me because i need 3 header rows.
$(document).ready(function() {
var table = $('#example').DataTable( {
lengthChange: false,
buttons: [{ extend: 'pdf', className: 'btn-success' },
{ extend: 'print', className: 'btn-success' },
{ extend: 'excel', className: 'btn-success' } ]
}
}
);
table.buttons().container()
.appendTo( '#example_wrapper .col-md-6:eq(0)' );
} );
Assumed you use the button for Excel export.
You thought about the excelHtml5, Option named messageTop ?
I would rather add the 3 additional header rows via buttons.exportData( [ options ] ).
There you have an option key customizeData:
function customizeData (since Buttons 1.5.2) - Function that can be used to modify the data used for the export, after all of it has been gathered and pre-processed by the above formatting options. A single argument is passed in and no return parameter is expected (mutate the object passed in to alter the data):
Data for export. This is an object with the following properties:
header - Array of data for the header
footer - Array of data for the footer
body - 2D array of data for the body.
For example add the 3 rows to this header array:
var table = $('#myTable').DataTable();
var data = table.buttons.exportData( {
customizeData: function(dataForExport) {
dataForExport.header.push("Header line 1");
dataForExport.header.push("Header line 2");
dataForExport.header.push("Header line 3");
}
} );
// Do something with the 'data' variable

Single check box selection with jquery datatable

In jquery datatable, single check box should be selected.
This link is working fine.
But above link is using jquery.dataTables 1.10.16 version. And I am using jquery.dataTables 1.9.4.
Can the same functionality as listed in example given above be possible with jquery.dataTables 1.9.4 instead of jquery.dataTables 1.10.16?
In the same page which you give the link, there are many explanation about to using "single check" oparetion.
At the end of the listed attachment, you can see the referanced .js file is
https://cdn.datatables.net/select/1.2.5/js/dataTables.select.min.js
In your page, you should add this file referance after dataTable.js.
I think, the version of jquery is not important. The important file is "dataTables.select.js"!
Secondly, you must update your dataTable maker codes like the sample below;
$(document).ready(function() {
$('#example').DataTable( {
columnDefs: [ {
orderable: false,
className: 'select-checkbox',
targets: 0
} ],
select: {
style: 'os',
selector: 'td:first-child' // this line is the most importan!
},
order: [[ 1, 'asc' ]]
} );
} );
UPDATES :
Why dont you try to write your own selector function?
for example;
$(document).ready(function() {
$('#example').DataTable( {
/// put your options here...
} );
$('#example').find("tr").click(function(){ CheckTheRow(this); });
} );
function CheckTheRow(tr){
if($(tr).find("td:first").hasClass("selected")) return;
// get the pagination row count
var activePaginationSelected = $("#example_length").find("select").val();
// show all rows
$("#example_length").find("select").val(-1).trigger("change");
// remove the previous selection mark
$("#example").find("tr").each(function(i,a){
$(a).find("td:first").removeClass("selected");
$(a).find("td:first").html("");
});
// mark the picked row
$(tr).find("td:first").addClass("selected");
$(tr).find("td:first").html("<i class='fa fa-check'></i>");
// re turn the pagination to first stuation
$("#example_length").find("select")
.val(activePaginationSelected).trigger("change");
}
Unfortunately, legacy data table does not support or have that select extension.
Workaround:
Create checkbox element inside 'mRender' callback.
Bind action to the checkbox. (This can be done inside the fnRowCallback or outside as in my example in below fiddle
https://jsfiddle.net/Rohith_KP/dwcatt9n/1/
$(document).ready(function() {
var userData = [
["1", "Email", "Full Name", "Member"],
["2", "Email", "Full Name", "Member"]
];
var table = $('#example').DataTable({
'data': userData,
'columnDefs': [{
'targets': 0,
'className': 'dt-body-center',
'mRender': function(data, type, full, meta) {
return '<input type="checkbox" value="' + $('<div/>').text(data).html() + '">';
}
}],
'order': [1, 'asc']
});
$('#example tr').click(function() {
if ($(this).hasClass('row_selected'))
$(this).removeClass('row_selected');
else
$(this).addClass('row_selected');
});
});
Also, I suggest you to upgrade your datatable version. Then you can use that select extension.
Can the same functionality as listed in example given above be possible with jquery.dataTables 1.9.4 instead of jquery.dataTables 1.10.16?
Yes.
But, not using the Select Extension since it requires at least version 1.10.7.
For 1.9.4, a possible solution would be:
$(document).ready(function() {
$('#example').find("td input[type='checkbox']").click(function() {
selectRow(this);
});
var table = $('#example').DataTable();
function selectRow(clickedCheckBox) {
var currentPage = table.fnPagingInfo().iPage;
// Being unchecked
if (!$(clickedCheckBox).is(':checked')) {
$(clickedCheckBox).removeAttr('checked');
getRow(clickedCheckBox).removeClass('selected');
return;
}
var selectEntries = $("#example_length").find("select");
var showEntriesCount = selectEntries.val();
var totalRows = table.fnGetData().length;
// If show entries != totalRows append total rows opiton that can be selected
if (totalRows != showEntriesCount)
selectEntries.append($('<option>', {
value: totalRows,
text: totalRows
}));
// Display all rows
selectEntries.val(totalRows).trigger("change");
// Removes all checked attribute from all the rows
$("#example").find("td input[type='checkbox']").each(function(value, key) {
getRow(key).removeClass('selected');
$(key).removeAttr('checked');
});
// Check the clicked checkBox
$(clickedCheckBox).prop('checked', true);
getRow(clickedCheckBox).addClass('selected');
// Re set the show entries count
selectEntries.val(showEntriesCount).trigger("change");
// If added, Remove the additional option added to Show Entries
if (totalRows != showEntriesCount)
selectEntries.find("[value='" + totalRows + "']").remove();
// Go to the page on which the checkbox was clicked
table.fnPageChange(currentPage);
}
function getRow(element) {
return $(element).parent().parent();
}
});
The above will require fnPagingInfo to take the user back to initial page. I haven't tested the solution on large dataset, tested it on a table with 150 rows, but should work fine on larger datasets too.
JSFiddle
Have you tried below code and I checked and it is working fine, you need to update styles and scripts:
You havr to update the latest styles and scripts to achieve latest functionality.
Single check box selection with jquery datatable

Datatables sorting based on radio button and checkboxes

I am using jQuery datatables. I am getting few values in JSON as columns in datatables. In two of those columns , one has only radio buttons and one has only checkboxes. I want to sort on the basis of checkboxes (like if the checkbox is checked it should appear first) and radio buttons. How can I do that?
See Live DOM ordering example.
/* Create an array with the values of all the checkboxes in a column */
$.fn.dataTable.ext.order['dom-checkbox'] = function ( settings, col )
{
return this.api().column( col, {order:'index'} ).nodes().map( function ( td, i ) {
return $('input', td).prop('checked') ? '1' : '0';
} );
}
/* Initialise the table with the required column ordering data types */
$(document).ready(function() {
$('#example').DataTable( {
"columns": [
{ "orderDataType": "dom-checkbox" }
]
} );
} );

jQuery datatables - Index Column print/download issue

I am using a jquery datatables api index column. I've managed to make the table work by following the documentation shown on the page.
I also used the Buttons plugin to print the table, but in the "index" -- or in my case I named it "Bil" -- column, the numbers are not printed out.
The same problem occurs when I want to view the data after downloading the table in Excel and PDF.
The output when I wanted to print the table:
I don't know if it is a bug or not since I can't find the issue raised else where. I suspect the index value was only loaded to the page but is not inserted into the table. Is there a workaround to maybe use javascript to insert the value inside the table's ?
Here is the datatable's javascript that is responsible for the indexing:
//Datatable
var t = $('#tablePelajarLama').DataTable({
dom: 'lBfrtip',
buttons: [
'copy', 'excel', 'pdf', 'print'
],
"columnDefs": [ {
"searchable": false,
"orderable": false,
"targets": 0
} ],
"order": [[ 1, 'asc' ]]
});
//index counter
t.on( 'order.dt search.dt', function () {
t.column(0, {search:'applied', order:'applied'}).nodes().each( function (cell, i) {
cell.innerHTML = i+1;
} );
} ).draw();
On a side note, I use PHP to load the data into the table if it in any way affects the process. Thanks.
SOLUTION
You need to use cell().invalidate() API method to tell DataTables to re-read the information from the DOM for the cell holding the index.
t.on( 'order.dt search.dt', function () {
t.column(0, {search:'applied', order:'applied'}).nodes().each( function (cell, i) {
cell.innerHTML = i + 1;
t.cell(cell).invalidate('dom');
} );
} ).draw();
DEMO
See this jsFiddle for code and demonstration.

How do I ignore HTML when filtering a jQuery data table?

I'm using the jQuery DataTables plugin, and having a slight problem with the filtering feature in it. If I have a table cell with content like <a href='foo6'>Blah</a>, and I filter for "6", that cell will show up, even though there is no "6" in "Blah". What I'd like to do is have the DataTables plug-in ignore HTML when doing it's filtering.
I've tried scouring the DataTables site, and found conflicting, un-helpful leads. One post suggested that I needed an sType:'html' option in the definition of my aaColumns, but I tried that and it didn't help ... plus a later post suggested that the current version of DataTables auto-detects the HTML sType. I also found this code snippet:
// Make filtering ignore HTML (see http://datatables.net/plug-ins/filtering)
$.fn.dataTableExt.ofnSearch['html'] = function ( sData ) {
var n = document.createElement('div');
n.innerHTML = sData;
if (n.textContent) {
return n.textContent.replace(/\n/g," ");
} else {
return n.innerText.replace(/\n/g," ");
}
};
which was supposed to fix things ... but it didn't.
So, my question is: does anyone out there know how to make DataTables ignore non-text (ie. HTML) content when filtering rows?
It turned out I needed a custom mRender function on my column headers. More importantly (since I had tried this at first without checking the "type" argument) you need to use the type argument provided to that function to make it only apply when filtering.
My end result looked something like this:
aaHeaders: [{
mRender: function(data, type, full) {
// If we're filtering, don't look at the HTML; only filter on the text
return type == 'filter' ? $(data).text() : data
}
}], //...
You can try this one :
$.fn.dataTableExt.ofnSearch['html'] = function ( sData ) {
return $("<div/>").html(sData).text();
}
Just upgrade your datatable.js.. I have used 1.9.4 and got the same problem after upgrading to 1.10.9 the problem resolved..
// To override basic search functionality of datatable
$.fn.dataTable.ext.search.push(
function( settings, data, dataIndex ) {
var tableId = settings['sTableId'];
var searchTerm = settings.oPreviousSearch.sSearch;
if ( 'tableId' == tableId){
//I added tableId condition as I have multiple table on same page..
if(data[0].indexOf(searchTerm) > -1 ||data[2].indexOf(searchTerm) > -1||data[3].indexOf(searchTerm) > -1||data[4].indexOf(searchTerm) > -1||data[5].indexOf(searchTerm) > -1 || data[6].indexOf(searchTerm) > -1){
return true;
}else{
return false;
}
}
return true;
}
);

Categories