JQuery Datatables Properties - javascript

I am working on a web project, where I have used JQuery Datatables in the project, the only challenge that I am facing with is, how to get or access datatable's properties and vlues like: search value, order, limit, ... using JavaScript and JQuery.
Thanks in advance.
Some Code I have Used:
function loadDestroyedGoods() {
var start_date = $("#start_date").val();
var end_date = $("#end_date").val();
if (start_date && end_date) {
var dataTable = $('.g_tbl').DataTable({
"processing": true,
"serverSide": true,
"destroy": true,
"lengthChange": true,
"lengthMenu": [20, 50, 100, 500, 1000],
"pageLength": 10,
"ajax": {
"url": "/loadGoodsDestroyed",
"type": "POST",
"dataType": "json",
"dataSrc": "data",
"data": {start_date: start_date, end_date: end_date}
},
"columns": [
{"data": "name"},
{"data": "status"},
{"data": "count"},
{"data": "price"},
{"data": "consumer"},
{"data": "date"}
]
});
}
}
This is what I want:
What I want is how to get data-tables' properties, not how to load custom data into it. I don't need server side engagement here, all I want is how to get the value which user entered for the search, the order user used to order the rows

you can add following line to your javascript to extract global search filter value. (if you are using same table that you linked, not changed any id of table).
here is code for search field on that page:
below query looks for example filter id in your page which is div id, inside that it looks for label tag, in it there is input type="search" , so i used below which extract the value of that search field.
$("#example_filter > label > input").val();
here is proof of its work :
and you can get sorting column name and index (it includes default sort on page load also) using this script :
$(document).ready(function (){
var table = $('#example').DataTable();
$("#example").dataTable().bind('click', function () {
var order = table.order();
alert( 'Table is ordered by column: '+order[0][0]+', direction:' + order[0][1]);
var title = table.column(order[0][0]).header();
alert( 'Ordering column title: '+$(title).html() );
});
var order = table.order();
alert( 'Table is ordered by column: '+order[0][0]+', direction:' + order[0][1]);
var title = table.column(order[0][0]).header();
alert( 'Ordering column title: '+$(title).html() );
});

Related

Prepopulate individual search column: Datatables

I have an application that will pass the filtering attributes in the url http://localhost/webpage/public/index.php?control_id=123&sample_id=234
I'm using javascript to identify the id:
const urlParams = new URLSearchParams(window.location.search);
const control_id = urlParams.get('control_id');
const sample_id = urlParams.get('sample_id');
I want to pass the control_id and sample_id in the column filtering field in my data table
cloumn filtering box
But I'm not being able to do so, I added "oSearch": {"sSearch": control_id}, to the data table, but this is filtering the universal search of the table.
universal search filtering
How can I filter data based on column filtering and not the universal filtering in data tables?
Appreciate your time.
--UPDATE--
This is the definition of data tables JS
const urlParams = new URLSearchParams(window.location.search);
$(document).ready(function() {
const control_id = urlParams.get('control_id');
// Setup - add a text input to each footer cell
$('#example tfoot th').each(function () {
var title = $(this).text();
$(this).html('<input type="text" placeholder="Search ' + title + '" />');
});
$('#example').DataTable( {
"oSearch": {"sSearch": control_id},
"processing": true,
"bFilter": true,
"searching":true,
"ordering": true,
"order": [[0, 'asc']],
"ajax": {
"url": "../model/Data.php",
"type": "POST",
"dataType": "json",
},
"columns": [
{data: 'control_id'},
{data: 'sample_id'},
{data: 'sample_nm'},
{data: 'sample_type_nm'},
{data: 'variant_type'},
{data: 'pipeline_status'},
{data: 'oncsuite_status'},
{data: 'control_completion_status'},
{data: 'send_oncsuite_status'},
{data: 'api_log_creation_dt'}
],
});
var table = $('#example').DataTable();
table.columns().every( function () {
var that = this;
$( 'input', this.footer() ).on( 'keyup change', function () {
that
.search( this.value )
.draw();
} );
} );
});
The version of datatbales is : 1.10.22
You have several errors in your code. First, you're initializing your DataTable more than one time. Instead, init it once and assign it to a variable, like so:
var myTable = $('#example').DataTable( {
"processing": true,
"searching":true,
"ordering": true,
"order": [[0, 'asc']],
"ajax": {
"url": "../model/Data.php",
"type": "POST",
"dataType": "json",
},
"columns": [
{data: 'control_id'},
{data: 'sample_id'},
{data: 'sample_nm'},
{data: 'sample_type_nm'},
{data: 'variant_type'},
{data: 'pipeline_status'},
{data: 'oncsuite_status'},
{data: 'control_completion_status'},
{data: 'send_oncsuite_status'},
{data: 'api_log_creation_dt'}
],
});
Then, to search filter by control_id and sample_id:
myTable.column(0).search(control_id).column(1).search(sample_id).draw();
To explain: myTable contains your DataTable object. You then define which column to search using the column index (which starts at 0 for the first column), and you can chain your filters together like I've shown above.
Notes:
This assumes you want an AND condition for your filter, so that the
results returned must have both filter criteria met (control_id AND
sample_id), which follows the logic of your url parameters.
This assumes that that variables control_id and sample_id are in
scope of the line of code above.
Here is a fiddle demo

jquery data table and sorting columns

I'm using jquery data table to display large amounts of data inside grid. I implemented server side pagination but I'm struggling with sorting data server side.
Below is my datatable initialization, answer with query for sorting is not the subject here, I just need a way to pass information of which column is clicked to the controller, the one upon I will do the sorting.
('#myTable').dataTable({
"processing": true,
"serverSide": true,
"info": false,
"pageLength": 10,
"lengthChange": false,
"stateSave": false,
"bPaginate": true,
"bFilter": false,
"sPaginationType": "full_numbers",
"info": "Page _PAGE_ from _PAGES_",
"infoEmpty": "No data",
"oPaginate": {
"sFirst": "First",
"sPrevious": "Previous",
"sNext": "Next",
"sLast": "Last"
},
"ajax": {
"url": "#string.Format("{0}://{1}{2}", Request.Url.Scheme, Request.Url.Authority, Url.Content("~"))/MyController/GetData",
"type": "GET",
"data": function (d) {
.....
},
},
preDrawCallback: function (settings) {
...
},
drawCallback: function (settings) {
...
},
"columns": [
{ "data": "Id" },
{ "data": "FirstName" },
{ "data": "LastName" },
{ "data": "Age" }
],
"columnDefs": [
{
targets: [0],
orderable: false
},
{
render: function (data, type, row) {
...
}
],
"order": [[0, "desc"]]
});
public ActionResult GetData(){
var sortColumn = ...
...
}
You can bind the 'order' event like this:
$('#myTable').on( 'order.dt', function () {
var order = table.order();
var column_selected = order[0][0];
var order_way= order[0][1];
doStuff(column_selected ,order_way);
});
See it in plugin reference
By specifying "serverSide": true,, datatables will by default add information to the request which you need to use in your server-side code. If you look in the Firebug Network panel, you will be able to see the request with the querystring parameters. See here for the full list of parameters. Note that the link is to the v1.9 documentation, because that's what it looks like you're using.
So for sorting, you'd be interested in iSortCol_0 and sSortDir_0 which relate to the clicked column and the sort direction respectively.
In your controller method, you would access the parameters like this:
var sortColumnIndex = Convert.ToInt32(Request["iSortCol_0"]);
var sortColumnDir = Request["sSortDir_0"];
You then need to incorporate this, and the other parameters into your query.
Here is an article on using server-side datatables with MVC

jquery datatables accessing variable in className

I am using JQuery Datatable plugin found here. I have the following piece of code. I have a line in my code with the following comment //I need to access the variable row.RECIBO here. In the className parameter below, I am trying to access a variable name so that I can distinguish my class using an ID. How can I accomplish that goal of mine?
var table = $('#tableCLIX1').DataTable({
"order": [[0, "desc" ]],
"ajax": {"url": "reciboBackend.php", "type": "POST", "dataSrc": "db" },
"columnDefs": [{
"render": function(data, type, row){ return row.RECIBO},
"targets": 8,
"className": "tranState" + VARIABLE //I need to access the variable row.RECIBO here
}],
"columns": [
{"data": "RECIBO", className: "recibo"},
{"data": "NOMCLI"},
{"data": "CLIENTE"},
{"data": "FECHA"},
{"data": "NUMPOL"},
{"data": "FACTURA"},
{"data": "TIPO"},
{"data": "VALOR"},
{"mRender": function(data, type, full){if(full["TRANSTATE"] == null) return "<button id = 'cancelar" + full["RECIBO"] + full["FACTURA"] + "' class='button-error pure-button cancelar-btn " + full["RECIBO"] + "' > Cancelar </button>"; else return full["TRANSTATE"];}},
{"mRender": function(data, type, full, meta){return ' Imprimir ';}}
],
"deferRender": true
});
NB: You both have a columns mRender and a columnDefs render method for column #8, why? There is something wrong with the code.
Anyway, className is static for all <td>'s in the column and does not support callbacks. render is strictly about content of the cell and cannot be used to add CSS, besides inside elements added as content.
But you can use rowCallback to post process the rendered row, and by that add a class to column #8 using the rows RECIBO value :
var table = $('#tableCLIX1').DataTable({
rowCallback: function(row, data, index) {
$('td:eq(8)', row).addClass('tranState'+data.RECIBO);
},
// ...
})

JQuery Datatables : Cannot read property 'aDataSort' of undefined

I created this fiddle to and it works well as per my requirements: Fiddle
However, when I use the same in my application I get an error in the browser console saying Cannot read property 'aDataSort' of undefined
In my application, the javascript reads something like as below: I have checked the controller output...it works well and is printed on the console too.
$(document).ready(function() {
$.getJSON("three.htm", function(data) {
// console.log("loadDataTable >> "+JSON.stringify(data));
})
.fail(function( jqxhr, textStatus, error ) {
var err = textStatus + ', ' + error;
alert(err);
console.log( "Request Failed: " + err);
})
.success(function(data){
loadDataTable(data);
});
function loadDataTable(data){
$("#recentSubscribers").dataTable().fnDestroy();
var oTable = $('#recentSubscribers').dataTable({
"aaData" : JSON.parse(data.subscribers),
"processing": true,
"bPaginate": false,
"bFilter": false,
"bSort": false,
"bInfo": false,
"aoColumnDefs": [{
"sTitle": "Subscriber ID",
"aTargets": [0]
}, {
"sTitle": "Install Location",
"aTargets": [1]
}, {
"sTitle": "Subscriber Name",
"aTargets": [2]
}, {
"aTargets": [0],
"mRender": function (data, type, full) {
return '<a style="text-decoration:none;" href="#" class="abc">' + data + '</a>';
}
}],
"aoColumns": [{
"mData": "code"
}, {
"mData": "acctNum"
}, {
"mData": "name"
}]
});
}
})
It's important that your THEAD not be empty in table.As dataTable requires you to specify the number of columns of the expected data .
As per your data it should be
<table id="datatable">
<thead>
<tr>
<th>Subscriber ID</th>
<th>Install Location</th>
<th>Subscriber Name</th>
<th>some data</th>
</tr>
</thead>
</table>
Also had this issue,
This array was out of range:
order: [1, 'asc'],
For me, the bug was in DataTables itself; The code for sorting in DataTables 1.10.9 will not check for bounds; thus if you use something like
order: [[1, 'asc']]
with an empty table, there is no row idx 1 -> this exception ensures.
This happened as the data for the table was being fetched asynchronously. Initially, on page loading the dataTable gets initialized without data. It should be updated later as soon as the result data is fetched.
My solution:
// add within function _fnStringToCss( s ) in datatables.js
// directly after this line
// srcCol = nestedSort[i][0];
if(srcCol >= aoColumns.length) {
continue;
}
// this line follows:
// aDataSort = aoColumns[ srcCol ].aDataSort;
I faced the same problem, the following changes solved my problem.
$(document).ready(function() {
$('.datatable').dataTable( {
bSort: false,
aoColumns: [ { sWidth: "45%" }, { sWidth: "45%" }, { sWidth: "10%", bSearchable: false, bSortable: false } ],
"scrollY": "200px",
"scrollCollapse": true,
"info": true,
"paging": true
} );
} );
the aoColumns array describes the width of each column and its sortable properties.
Another thing to mention this error will also appear when you order by a column
number that does not exist.
In my case I had
$(`#my_table`).empty();
Where it should have been
$(`#my_table tbody`).empty();
Note: in my case I had to empty the table since i had data that I wanted gone before inserting new data.
Just thought of sharing where it "might" help someone in the future!
In my case I solved the problem by establishing a valid column number when applying the order property inside the script where you configure the data table.
var table = $('#mytable').DataTable({
.
.
.
order: [[ 1, "desc" ]],
You need to switch single quotes ['] to double quotes ["] because of parse
if you are using data-order attribute on the table then use it like this data-order='[[1, "asc"]]'
Most of the time it occurs when something is undefined. I copied the code and removed few columns which disturbed the order by index. Carefully make changes and every variable after it.
"order": [[1, "desc"]], fixed my issues previous i was using "order": [[24, "desc"]], and that index was not avaialble.
I had this problem and it was because another script was deleting all of the tables and recreating them, but my table wasn't being recreated. I spent ages on this issue before I noticed that my table wasn't even visible on the page. Can you see your table before you initialize DataTables?
Essentially, the other script was doing:
let tables = $("table");
for (let i = 0; i < tables.length; i++) {
const table = tables[i];
if ($.fn.DataTable.isDataTable(table)) {
$(table).DataTable().destroy(remove);
$(table).empty();
}
}
And it should have been doing:
let tables = $("table.some-class-only");
... the rest ...
I got the error by having multiple tables on the page and trying to initialize them all at once like this:
$('table').DataTable();
After a lot of trial and error, I initialized them separately and the error went away:
$("#table1-id").DataTable();
$("#table2-id").DataTable();
My Solution
add this :
order: 1 ,
For me
adding columns in this format
columns: [
{ data: 'name' },
{ data: 'position' },
{ data: 'salary' },
{ data: 'state_date' },
{ data: 'office' },
{ data: 'extn' }
]
and ajax at this format
ajax: {
url: '/api/foo',
dataSrc: ''
},
solved for me .
Old question, but in my case I was passing an unrelated order= in the URL that would sometimes be empty. Once I changed the url variable to "sortorder" or anything other than "order" the plugin began working normally.
I got the same error, In my case one of the columns was not receiving proper data. some of the columns had strings in place of Integers. after i fixed it it started working properly. In most of the cases the issue is "table not receiveing proper data".
Just my two cents regarding order: [...];
It won't check items type, and in my case I was passing [arrOrders] as opposed to just arrOrders or [...arrOrders], resulting in [[[ 1, "desc" ], [ 2, "desc" ]]].

Sorting on a column in removing html contents in Datatables 1.10

I am unsing datatable 1.10, In my code in one of the column as per the requirement I am adding an HTML checkbox tag.
Now first time when the table gets rendered it shows me those checkboxes but when I click on that column to sort or any other column for sorting then the column which contains HTML contains are getting wiped out. (I crosschecked this with the chrome DOM inspector... the td element contains nothing :()
Below is my dataTable initialization code.
dataTableOptions: function() {
return {
"orderable": true,
"columnDefs": undefined,
"autoWidth": true,
"deferRender": true,
"data": undefined
};
},
dtRowGroupingOptions: function () {
return {
bExpandableGrouping: true,
bExpandSingleGroup: false,
iExpandGroupOffset: -1,
asExpandedGroups: [""]
};
}
var dataTablesOptions = self.dataTableOptions();
dataTablesOptions.data = tableData;
dataTablesOptions["paginate"] = false;
dataTablesOptions["lengthChange"] = false;
dataTablesOptions["columnDefs"] = [{"targets": 0, "data": "serverName", 'title' : 'ServerName'},
{"targets": 1, "data": "COMMAND", 'title' : 'Command'},
{"targets": 2, "data": "PID", 'title' : 'Process Id'},
{"targets": 3, "data": "SIZE", 'title' : 'Size'},
{"targets": 4, "data": "USER", 'title' : 'User'},
{"targets": 5, "data": "action", 'title' : 'Actions', "type" : "html", "orderDataType": "dom-checkbox"}
];
dataTablesOptions["createdRow"] = function (nRow, aData, iDataIndex) {
var self = this;
if (aData["comments"] && aData["comments"].indexOf("Error") != -1) {
// Do not do anything
$('td:eq(0)', nRow).html(aData["serverName"]+"" +
"<a class='btn btn-danger' href='#' data-toggle='tooltip' title='Error in execution'><i class='icon-question'></i></a>");
}
return self;
};
var dcInfoDataTable = contentDiv.find('table.dcInfoTable').DataTable(dataTablesOptions);
I am also using datatables rowGrouping and searchhiglight plugin, below is the code.
// call row grouping
contentDiv.find('table.dcInfoTable').dataTable().rowGrouping(self.dtRowGroupingOptions());
// enable search highlighing
contentDiv.find('table.dcInfoTable').dataTable().fnSearchHighlighting();
Note: I tried removing rowGrouping plugin code just to make sure that this is not happeing because of this plugin but even after removing there is no effect, the HTML contents are getting wiped out.
Not only when you sort will it clear out your data, it will also clear it if you use any other feature that changes your table. This happens because each time the datatable draws for new data, it's clearing out your static data.
You need to re-append the checkboxes on each draw, you can do this in the fnDrawCallback event:
$(document).ready( function() {
$('#example').dataTable( {
"fnDrawCallback": function( oSettings ) {
alert( 'DataTables has redrawn the table' );
//append the checkbox to your table columns here...
}
} );
} );

Categories

Resources