DataTables - Sorting not working after content update - javascript

I'm using DataTables (version 1.10.18) and I'm updating rows and its content via jQuery.
My table is initalized with this code:
$(".summary").append(tableContent);
var otable = $('.summary').DataTable({
initComplete: function () {
this.api().columns([0, 1, 2, 3]).every(function () {
var column = this;
var select = $('<select><option value=""></option></select>')
.appendTo($(column.footer()).empty())
.on('change', function () {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);
column
.search(val ? '^' + val + '$' : '', true, false)
.draw();
});
column.data().unique().sort().each(function (d, j) {
select.append('<option value="' + d + '">' + d + '</option>')
});
});
},
"pageLength": records_per_page,
"language": {
"url": "//cdn.datatables.net/plug-ins/1.10.16/i18n/Italian.json"
},
"order": [[0, 'desc']],
"ordering": true,
"scrollX": true,
"scrollY":"50vh",
"searching":false,
"info":false,
"paging": false
});
Then I've an input field that searches in a SharePoint list (via Rest API). So I make an AJAX call, I get the response from SharePoint web service and I prepare HTML code with new data (some data returned from web services needs to be modified). Finally I update the table content using this code:
var otable = $('.summary).DataTable();
otable.clear().draw();
$(".dataTables_scrollBody>.summary").append(newContent);
otable.rows().invalidate().draw();
newContent is something like:
newContent = "<tbody><tr><td>content</td><td>content</td></tr></tbody>";
Content is updating correctly and sorting arrows are visible in the table header, they are also changing their own active status (desc or asc) but content is not sorted.
I've tried a lot of solutions found online but no one is working for me. In the content update section I'm also adding rows using .append() method.
Is there a way to fix this?

i would suggest, instead of appending the row, you should use the https://datatables.net/reference/api/row.add() add method which is exposed by datatable api. This will automatically apply all the initial settings to new added row.

Related

jQuery get all rows using table.rows().data().each with pagination

I can't find a solution online for this. I have my code like this
$('.validation-summary-table').dataTable({ paging: true, ordering: false });
const conflictsArray = pushConflictDatas('#conflict .validation-summary-table tbody tr.odd');
function pushConflictDatas(dataTableTr) {
let radioButtonsConflicts = new Array();
$(dataTableTr).each(function() {
const currentRow = $(this).closest("tr"); // CSV row
const nextRow = currentRow.next(); // DB row
let currentRowObj = {
Name: currentRow.find('td:eq(0)').text().trim(),
isChecked: currentRow.find('td:eq(1) input[type="radio"]').is(':checked')
}
let nextRowObj = {
Name: nextRow.find('td:eq(0)').text().trim(),
isChecked: nextRow.find('td:eq(1) input[type="radio"]').is(':checked')
}
radioButtonsConflicts.push([currentRowObj, nextRowObj]);
});
return radioButtonsConflicts;
}
This worked fine until I found out it wasn't getting all table rows on the next pages when I click a button, only the current page and nothing else. I need to get all the rows and push them to an array for my ajax request. So I found this code from their docs:
var table = $(conflictTable).DataTable();
table.rows('.odd').data().each(function (value, index) {
console.log('index: ', index)
console.log('value: ', value)
} );
However this only selects <tr> on the current page, just like what the old function does. If I move to the next page, it will "append" it. If I remove the selector .odd, it would get all the rows from all paginated pages, but I'm writing a code that targets the next row and I want to only select rows with a specific class name before I do such. How do I do this?
You can use the following code to get all table data:
let table_data = table.rows({ search: 'applied'}).data();

JS Datatables - filtering table from combo box in header

I have the following datatable which uses the js datatable plugin from https://datatables.net/
The datatable is set using the following JS:
$(document).ready(function () {
$('#tracerTable').DataTable({
"bInfo": false,
"order": [[2, "desc"]], //order by date created
"aoColumnDefs": [
{ aTargets: [3], "bSortable": false },
{ aTargets: [4], "bSortable": false },
{ aTargets: [5], "bSortable": false }
]
});
}
Question:
Is it possible to update the JS to allow me to filter on the 'Type' column using a dropdown with tickbox options within in the table header (just like the filter option in excel - see image below). I would want this for selecting Water and Oil Tracers, but not showing Gas tracers.
If this is not possible within the datatable plugin, can anyone suggest a plugin which would provide this functionality?
Make use of the bootstrap-select plugin, append it to the header of your DataTables by targeting the desired column (in your case 1), get the checked values, join it with | (the or operand) then use search API.
var table = $('#example').DataTable({
initComplete: function() {
this.api().columns([1]).every(function() {
var column = this;
var select = $('<select class="selectpicker" data-show-content="false" data-none-selected-text="Position" multiple><option value="" >Show All</option></select>')
.appendTo($(column.header()).empty())//use $(column.footer() to append it to the table footer instead
.on('changed.bs.select', function(e) {
var val = $(this).val();
var fVal = val.join("|")
column
.search(fVal, true, false)
.draw();
}); //select
column.data().unique().sort().each(function(d, j) {
select.append('<option value="' + d + '">' + d + '</option>')
}); //column.data
}); //this.api
} //initComplete
});
Fiddle for more details, I suggest moving the filter function on the footer as clicking the dropdown button on the table header will sort the table.

DataTables - how to render data with custom tag

This is how I use my custom tag in JSP
<utility:displayStatus value="${consumerForm.status }" />
When it comes to DataTables, I try to render the column like this :
"columnDefs": [
{
"targets": [ 0, 1 ],
"render" : function ( data, type, row ) {
var renderer = '';
renderer += '' + data + '';
return renderer;
}
},
{
"targets": 5,
"searchable": false,
"orderable": false,
"type" : "html",
"render" : function ( data, type, row ) {
var renderer = '<utility:displayStatus value="'+ data+'" />';
console.log(renderer)
return renderer;
}
},
I can get the html link display correctly in the datatables, but
'<utility:displayStatus value="'+ data+'" />'
cannot be rendered.
I tried with other html tag like label, span and button....and the result is correct.
Is it anyway to let the datatables render the custom tag correctly? Or Datatables is not support for custom tag such as JSTL ?
Thanks.
Browser want allowed you to display custom tags.
You can put your data in html tag's attribute like .
You can show/hide or customize your html tag in JS according to your data. Even you can access data-DepartmentCode further after rendering.
Cheers......

jQuery DataTable exact match

I have this jQuery datatable in place:
var $dataTable = $('#example1').DataTable({
"ajax": serviceUrl,
"iDisplayLength": 25,
"order": [[ 2, "asc" ]],
"scrollY": 600,
"scrollX": true,
"bDestroy": true
});
I also have this CHANGE event happening when the user selects an option in a dropdown:
$('#serviceload').on('change',function()
{
$dataTable.columns(1).search( this.value ).draw();
});
I need to be able to alter the CHANGE event so that it searches the DataTable for the exact match in the dropdown.
For example, the v has 2 services called SERV and SERV_ONE. In the dropdown, both SERV and SERV_ONE are available for the user to choose, but if the user chooses SERV, the datatable filters for SERV and also displays the records for SERV_ONE. But when SERV_ONE is chosen, the DataTable only displays the records for SERV_ONE.
See this example for proper use of drop-down filters.
$('#serviceload').on('change keyup', function(){
var val = $.fn.dataTable.util.escapeRegex($(this).val());
$dataTable
.columns(1)
.search( val ? '^' + val + '$' : '', true, false )
.draw();
});

DataTables - Getting the database ID of the current row via click event

I am trying to get the database ID of the current row while clicking a button.
I have seen a few examples relating to this aspect and have tried many but it seems that they mostly relate to the legacy table tools extension whereas I am making use of the Editor.
Using the idSrc option from the Editor manual I recieve a server side response in JSON that contains the databases id/primary key value:
{
"data":[
{
"id":"1",
"name":"Test Name",
}
],
"options":[],
"files":[]
}
Now I am trying to get that value by clicking a button that is attached to row via the API function: row().id()
Within the example for this function it provides a clear example of how the rows id value (now the database id?) can be obtained:
var table = $('#myTable').DataTable();
$('#myTable').on( 'click', 'tr', function () {
var id = table.row( this ).id();
alert( 'Clicked row id '+id );
});
So I have implemented this as follows:
var editor;
$(document).ready(function() {
editor = new $.fn.dataTable.Editor( {
ajax: "/names.php",
table: "#example",
idSrc: "id",
fields: [ {
label: "Name:",
name: "name"
} ]
});
var table = $('#example').DataTable( {
dom: "Bfrtip",
ajax: "/names.php",
columns: [
{ data: "name" }
]
});
$('#example').on( 'click', 'tr', function () {
var id = table.row( this ).id();
alert( 'Clicked row id ' + id );
});
});
The problem here though is that when I click on the row (tr) it prompts as follows: Clicked row id undefined
Why am I getting back an undefined value when it should be sending back the row id?
When instances your DataTable, you must indicate the id field rowId, which should be indicated as the name of your columns
var table = $('#example').DataTable( {
dom: "Bfrtip",
ajax: "/names.php",
columns: [
{ data : "id" },//id is the name of your data
{ data: "name" }
],
rowId: 'id' //Here assign the id to your table
});
Result: https://jsfiddle.net/cmedina/7kfmyw6x/17/
As #CMedina pointed out, rowId stipulates which value in the JSON data is used as each rows id attribute.
Here is the code used to get the rows ID value which is prefixed with row_:
$('#example').on( 'click', 'tr', function () {
// Get the rows id value
var id = table.row( this ).id();
// Filter for only numbers
id = id.replace(/\D/g, '');
// Transform to numeric value
id = parseInt(id, 10);
// So instead of returning the actual id which is row_1
// We get back just the primary key which is 1
alert( 'Clicked row id '+id );
});

Categories

Resources