DataTables Add Row missing data - datatables

When I run the following code with varying amounts of data, only a subset of the rows are added.
In the following example, the createdRow callback is always called the same amount of times as elements in the array of rows (ie. 5 out of 5). However, the rowCallback callback is only called a subset of those times(ie. 3 out of 5). I'll pass 5 rows and 3 will be added or 13 rows and 8 will be added. I can't figure out a pattern to it.
I've upgraded dataTables to the most recent version (1.10.9). I've tried adding the rows one at a time in a loop.
Any ideas? Thanks!
sub_table = $('#data-table-check-off').DataTable({
"dom": 'ft',
"oLanguage": { "sSearch": "", "sSearchPlaceholder": "Search" },
"sScrollY": "250px",
"stateSave": true,
"lengthChange": false,
"paging": false,
"rowCallback": function(row, data, index) {
console.log("in rowCallback");
},
"createdRow": function(row, data, index) {
console.log("in createdRow");
}
});
var rows = [["12","Lorenzo"],["14", "Holly"],["15", "Chad"],["16", "Bear"],["17", "Zack"]];
sub_table.rows.add(rows).draw(false);

Related

DataTable Sorting Issue (Instead of 1st row taking 2nd row for sorting)

I have a dataTable and it has two rows in table header. One row is the column names while the other one is the input fields
I dont know but by default the sorting is being done on the input fields (2nd row) rather that the label fields (1st row)
My code for the datatable is
$('#result-table').DataTable({
"paging": true,
"lengthChange": false,
"searching": true,
"ordering": true,
"info": true,
"autoWidth": false,
"responsive": true,
});
I am cloning the header row and adding the input field as
$("#result-table thead tr").clone(true).appendTo("#result-table thead");
// add a text input filter to each column of the new row
$("#result-table thead tr:eq(1) th").each(function (i) {
var title = $(this).text();
$(this).html("<input type='text' class='form-control' placeholder='Search '" + title + "' />");
$("input", this).on( "keyup change", function () {
if ($("#result-table").DataTable().column(i).search() !== this.value) {
$("#result-table").DataTable().column(i).search(this.value).draw();
}
});
});
What's wrong?
Here are 2 things you need to make sure you are doing:
Make sure the clone() code and the code to create input fields is placed inside the $(document).ready(function() code - but it must be placed before the $('#result-table').DataTable({...}) code.
Make sure your DataTables initialization includes this option:
orderCellsTop: true,
You may already be doing (1) - but (2) is missing from the code in the question.

DataTables Pager Showing Many Pages when there is Only One

This is a weird one.
I'm using datatables v1.10.19 with jQuery 3.3.1 and Bootstrap 3.3.7
My datatables grid is configured to display 1000 records (but you can change it to 2500, 5000 and "all").
I've only got about 60 records in my database.
It is using Server-Side processing to retrieve data.
When the grid loads, the pager displays 5 buttons plus an ellipses (as if there is even more).
And even weirder, if I change the drop-down to display "all" records, it acts as I would expect i.e. the pager has 1 page button.
The payloads are pretty much identical:
{
"data": {
"draw": 8,
"recordsTotal": 86,
"recordsFiltered": 66,
"data": [rows of data here]
},
"outcome": {
"opResult": "Success",
"message": ""
}
}
When you click on page 2, it does successfully retrieve a payload with 0 rows.
But there shouldn't be a page 2 available on the pager.
The config object for the datatable looks like this:
eventsSvr.buildConfig = function (url) {
return {
"processing": true,
"serverSide": true,
//"paging": true,
"ajax": {
url: url,
type: ajax.requestPOST,
dataSrc: 'data.data' // the path in the JSON structure to the array which will be the rows.
},
"order": [[1, "asc"]],
"lengthMenu": [[1000, 2500, 5000, -1], [1000, 2500, 5000, "All"]],
"initComplete": function (settings, json) {
eventsSvr.searchTextSpan.text('Search').removeClass('search-is-on');
},
"columns": eventsSvr.grid.columns,
"columnDefs": eventsSvr.grid.columnDefs,
dom: 'ltp'
};
I do have a bunch of custom searches on the page, so I've had to write a lot of code like this:
$.fn.dataTable.ext.search.push(
function (settings, data, dataIndex) {
var picker3 = $(eventsSvr.datePickerInputs[0]).data(icapp.kendoKey);
var picker4 = $(eventsSvr.datePickerInputs[1]).data(icapp.kendoKey);
var rowStartDate = moment(data[3], icapp.date.momentParseFormat).toDate();
var rowEndDate = moment(data[4], icapp.date.momentParseFormat).toDate();
... etc.
}
);
But the odd thing is the different behavior as between "All" records vs 1000 records.
As described above, select "All" records works (resulting in just 1 page button), but none of the other paging sizes work (i.e. 1000, 2500, 5000). The data for the 1 page does return, but I get 5 page buttons and an ellipses.
Any ideas why this would be happening?
When using server-side processing mode DataTables expects draw, recordsTotal and recordsFiltered to be root-level elements. Consider changing your repsonse to the following and you can remove dataSrc option.
{
"draw": 8,
"recordsTotal": 86,
"recordsFiltered": 66,
"data": [rows of data here],
"outcome": {
"opResult": "Success",
"message": ""
}
}
Alternatively you can manipulate the response before passing it to DataTables using function supplied as value for dataSrc option, but I would recommend keep things according to expected format for more readable code.

Chaining yadcf multi_select filters together

Is there a way to chain filters together where by filters applied in one column will pre-filter the available filters in other columns? Primarily I'm interested in this from a multi_select standpoint, but it could be universal to all filters types I guess.
For example:
Column 1's data contains:
Oklahoma
Missouri
Utah
Texas
Kansas
Column 2's data contains:
Obama
Romney
From the dataset I know that all Column 1 data that has 'Oklahoma' will always mean that Column 2 will equal 'Romney'. Thus, if I select 'Oklahoma' from a mutli_select, then the drop down for the multi_select for Column 2 should now only show 'Romney'.
Basically, can I pre-filter my filters based on other filters already put in place?
I think you are asking about the cumulative_filtering: true option of yadcf,
See the showcase page and here a code sample:
$(document).ready(function () {
'use strict';
var oTable;
oTable = $('#example').DataTable();
yadcf.init(oTable,
[
{
column_number : 0,
filter_type: "multi_select",
select_type: 'select2'
},
{
column_number: 3,
filter_type: "auto_complete",
text_data_delimiter: ","
},
{
column_number : 4,
filter_type: "multi_select",
select_type: 'select2',
column_data_type: "html",
html_data_type: "text",
filter_default_label: "Select tag"
}
],
{
cumulative_filtering: true
}
);
});
As you see the cumulative_filtering: true is an object property, an object that that is a third argument of the init function, when using the .yadcf([{...}]) api you should pass that object as a second arument to the .yadcf constractor, like this:
.yadcf([{...}], {cumulative_filtering: true})

jQuery Datatables highlighting row

I'm using datatables version 1.9.4 and am having a problem with adding a class to certain rows.
I have multiple datatables, all with class 'display'. I'm using jQuery tabs to display each datatable on a separate tab.
All is working well, except I want to add a class to a table row depending on the column values; if column 6 is less than column 14, I want to add myClass.
I've found suggestions to use fnRowCallback, but I'm getting random results, such as sometimes if column 6 is less than column 14, myClass gets added correctly, but other times if column 14 is less than column 6 myClass still gets added!
This doesn't happen for all rows though, so it's pretty random.
Here's the code I'm using
$(document).ready(function() {
$('.display').dataTable({
"bJQueryUI": true,
"sPaginationType": "full_numbers",
"bProcessing": true,
"bServerSide": true,
"bScrollCollapse": true,
"sScrollY": "300px",
"sAjaxSource": "ajax.php",
"sDom": '<"H"lfr>t<"F"ipS>',
"oScroller": {
"loadingIndicator": true
},
"fnRowCallback": function( nRow, aData ) {
var $nRow = $(nRow);
if (aData[6] < aData[14]) {
$nRow.addClass("myClass");
}
return nRow
}
});
});
Is there something wrong with what I've done, or is it because I'm using multiple tables?
I think I have this working, but there is probably a cleaner way, so if anyone knows of a better way of doing this, please let me know!
I'm looping through all the rows for each table once the table has been drawn.....
"fnDrawCallback": function( oSettings ) {
for (var i = 0, row; row = oSettings.nTable.rows[i]; i++) {
price = Number(row.cells[4].innerHTML.replace(/[^0-9\.]+/g,""));
average = Number(row.cells[6].innerHTML.replace(/[^0-9\.]+/g,""));
if (price < average) {
row.className = row.className + " myClass";
}
}
}

datatables column header reflect value used to sort

I've got datatables set up with about 10 columns, two of which do customized filtering when clicking the column headers.
I'd like to change the column header to reflect which filter is currently active.
To do it, I think I'll need to set up fnDrawCallback and look at the values returned by table.fnSettings()
My current code, trimmed to its essentials for this question:
var table = $('#units').dataTable({
"aaSorting": (popSearch) ? [[8,"asc"]] : [],
"aoColumns":[{ "bSortable": false },
{ "bSortable": false },
{ "asSorting": [ "", "on", "off", "occ", "none" ] },
null,
null,
{ "asSorting": [ "", "revised", "new" ] },
null,
null,
{ "bSortable": false },
{ "bSortable": false }
],
"oSearch": {"sSearch": searchString},
"sAjaxSource": "/system/units/data.php?1.4.3"
},
"fnDrawCallback": function() {
/* tweak column headers according to the asSorting value */
}
});
The asSorting arrays in the aoColumns array show the list of different filters that may be applied to the data being fed to datatables. If the third column header (Status) is clicked, I'd like its text to match what data was sent, (falling back to "status" if the empty string was sent). The filtering works, fine; I just want the header to reflect the applied filter.
In Datatables fnDrawCallback function, how do I know what values were sent for column sorting?
To enable which Column is being Sorted, and visually see it, all you should have to do is add the
"bSortClasses": true,
To your Data Tables Script. Such as:
"aaSorting": (popSearch) ? [[8,"asc"]] : [],
"bSortClasses": true,
...
You should see which column, is being used as the sorter. :)