Prepopulate individual search column: Datatables - javascript

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

Related

append column data outside the datatable container

I am using JQuery datatable, after loading the data from server, my table looks something like this:
As you can see my table has six columns. The last column which is Contracted product, has the same data inside, I want to get the value and display it outside the datatable so it becomes more reader friendly as shown in picture 2.
My code looks like this:
var table = $('#products').DataTable( {
"processing": true,
"serverSide": true,
"paging": true,
"scrollX":"true",
"ordering": [],
"stateSave": false,
"info": true,
"dom": 'lrtip',
"ajax":
{
url:"xxxxxx_fetch.php",
type:'POST'
},
"columns": [
{ data: "product_code_fk" },
{ data: "product_name" },
{ data: "start_date" },
{ data: "end_date" },
{ data: "pack_size" },
{ data: "contract_prod" }
],
} );
Through the use of the header and footer callback manipulation functions provided by DataTables (headerCallback and footerCallback).
in HTML, by exemple
<tfoot>
<tr>
<th colspan="4" style="text-align:right">CONTRAT PROD :</th>
<th></th>
</tr>
</tfoot>
DataTable
$('#example').DataTable( {
"footerCallback": function ( row, data, start, end, display ) {
let api = this.api(), data;
...
$( api.column( 4 ).footer() ).html(
your_DATA
);

DataTables adding data-order

I'm trying to sort my table by adding data-order in createdCell callback - it's working fine but seems table cache is not updating after that - sorting by first column (date with timestamp in data-order) simply not working.
I have tried table.rows/cells().invalidate() - no effect.
$.ajax({
type: "POST",
url: getLayoutData().urls.get_validation_history,
data: {
build_pk: build_pk,
type: validation_type,
},
success: function(response){
var response_data = JSON.parse(response);
var table = $("#validationHistoryTable").DataTable({
data: response_data.snapshots,
destroy: true,
autoWidth: false,
columns: [
{data: 'updated'},
{data: 'updated_by'},
{data: 'type'},
{data: 'status'},
{data: 'comment'},
],
columnDefs: [
{"width": "30%", "targets": 4},
{"targets": 0,
"createdCell": function(td, cellData, rowData, row, col){
raw = $(td).text().split(" ");
date = raw[0].split(".");
iso_time = date[2]+'-'+date[1]+'-'+date[0]+' '+raw[1];
$(td).attr('data-order', Date.parse(iso_time).getTime());
}
}
],
You cannot insert orthogonal data by manipulating nodes. You can manipulate existing and recognized data-* values through nodes and invalidate(), but not as part of the post processing of DOM nodes. Look at https://datatables.net/manual/data/orthogonal-data. data-* values can be specified by
Markup
A render literal that points to an alternative JSON property
A render callback
See proof of concept in this little example -> http://jsfiddle.net/rtu0bjz6/
{
targets: 2,
createdCell: function(td, cellData, rowData, row, col){
counter++
$(td).attr('data-order', counter)
}
}
Does not have any effect. The column is sorted by its original data, not its data-order. However, if you are using a render() function and return a special value upon type "sort" then it works as expected.
{
targets: 3,
render: function ( data, type, row, meta ) {
return type == 'sort' ? meta.row : data
}
}
So in your case, you could do something like (not tested) :
{
targets: 0,
render: function ( data, type, row, meta ) {
if (type == 'sort') {
var raw = data.split(" ");
var date = raw[0].split(".");
var iso_time = date[2]+'-'+date[1]+'-'+date[0]+' '+raw[1];
return Date.parse(iso_time).getTime()
} else {
return data
}
}
}

JQuery Datatables Properties

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() );
});

JQuery Data table - Get a value of a different column from another column

How do I get the value of checklistclient_id column and insert into the onchange event at the last column?
When the change of checkbox value occurs, it brings the checklistclient_id to the togglecheck function.
function loadClientChecklist(url){
var rt_hash = decodeUrl(url);
var id = rt_hash[0].replace("id=", "");
$.ajax({
type: 'POST',
url: '../model/get_set_ajax2.php?req=21',
data: 'cid=' + id,
success: function (results) {
console.log(results);
$('#clchecklist_tab').DataTable({
"paging": false,
"searching": true,
"info": false,
"ordering": false,
"aaData": $.parseJSON(results),
"aoColumns": [
{"mData": "checklistclient_id", "visible": false},
{"mData": "description"},
{"mData": "is_checked", "mRender": function (data) {
return '<input type="checkbox" onchange="togglecheck('+ checklistclient_id +')" value='+data+'/>';
}
}
]
});
}
});
You should use row created callback Then you can set id to trs.
"createdRow": function ( row, data, index ) {
$(row).data("checklistclient_id", checklistclient_id );
}
Now, you know all id of tr. Lets say that your check box has class called cb
$("#clchecklist_tab" ).delegate( ".cb", "change", function() {
togglecheck($(this).closest("tr").data(checklistclient_id))
})"

How to change jquery datatable value by dropdown value change

I am using jquery datatable to display table data based on dropdown list value, I am using ajax to get data from the table.
The problem is when the table first loads it is working fine but when I click on sort or search it displays processing which does not change until i refresh the page,the code is given below:
$( document ).ready(function() {
var table = $('#example').DataTable({
//"bProcessing": true,
//"sAjaxSource": "response.php",
"processing": true,
"serverSide": true,
//"bDestroy": true,
// "bJQueryUI": true,
"aoColumns": [
{ mData: 'FNAME' } ,
{ mData: 'FPRICE' },
{ mData: 'IMGPATH' },
{ mData: 'FDESC' },
{ mData: 'CID' }
],
"ajax": {
'type': 'POST',
'url': 'response.php',
'data': {id: $('#myselect').val()}
// "success":function (res) {
//
// }
}
});
$('#myselect').change(function() {
var item = $(this).val();
// alert(item)
var urld = 'response.php/'+item;
table.ajax.url(urld).load();
table.reload();
});
// setInterval( function () {
// table.ajax.reload();
// }, 10000 );
//table.fnDraw();
});
If you are using serverside processing check this out for custom sort https://datatables.net/forums/discussion/9857/server-side-processing-custom-sort-solution-like-formatted-num-sorting-plug-in

Categories

Resources