Datatables programmatically apply filter - javascript

I used the datatables jquery plugin to display a list which is loaded using an ajax call to the server.
I used the bFilter property in order to hide the filter because I want to put the search input inside my sidebar.
$(function () {
var generatedCustomerTable = $('#ItemsTable').DataTable({
"order": [[0, "desc"]],
"bSort": true,
processing: true,
serverSide: true,
ajax: {
url: "/api/Ajax/Test",
method: "POST",
},
columns: [
{ visible: false, data: "id" },
{ orderable: false, data: "name" },
{ orderable: false, data: "value" },
],
bLengthChange: false, // Hide the page size
bFilter: false, // Hide the search box
ordering: true,
paging: true,
pagingType: "full_numbers",
pageLength: 10,
language: {
paginate: {
first: '«',
previous: '‹',
next: '›',
last: '»'
},
aria: {
paginate: {
first: 'First',
previous: 'Previous',
next: 'Next',
last: 'Last'
}
}
}
});
$("#btnTest").click(function () {
// I WANT HERE TO SET THE FILTER
generatedCustomerTable.draw();
});
});
I want programmatically to set the filter text but I have not found a way to do it.
Is there some kind of function which will allow me to set the filter value so that I will be able to call the .draw() method in order to refresh the contents of the list.

In your code , By setting the bFilter to false will not only hide the search box but it'll disable also the search function from the dataTable ,
In order to create your own custom search box , you have to enable the bFilter, and then either hide the default search control with css (recommended ) by setting :
.dataTables_filter {
display:none;
}
, or you make your own table rendering using sDom | other link
See below Snippet :
var dataSet = [
[ 1, "Name 1","one" ],
[ 2, "BRimos", "JS" ],
[ 3, "pitaridis","Data" ],
[ 4, "Stack", "overflow" ],
[ 5, "Name 2","two" ],
[ 6, "Name 3","three" ],
[ 7, "Name 4","one" ],
[ 8, "BRimos 2", "JS" ],
[ 9, "pitaridis 2","Data" ],
[ 10, "Stack 2", "overflow" ],
[ 11, "Name 5","two" ],
[ 12, "Name 6","three" ]
];
$(function () {
var generatedCustomerTable =$('#ItemsTable').DataTable( {
"order": [[0, "desc"]],
"bSort": true,
data: dataSet,
columns: [
{ visible: false,title: "id" },
{ orderable: false,title: "name" },
{ orderable: false,title: "value" }
],
bLengthChange: false, // Hide the page size
bFilter: true, // Hide the search box
ordering: true,
paging: true,
pagingType: "full_numbers",
pageLength: 5,
language: {
paginate: {
first: '«',
previous: '‹',
next: '›',
last: '»'
},
aria: {
paginate: {
first: 'First',
previous: 'Previous',
next: 'Next',
last: 'Last'
}
}
}
} );
$("#btnTest").click(function () {
console.log($("#filter").val(),generatedCustomerTable);
generatedCustomerTable
.search($("#filter").val()).draw();
});
});
.dataTables_filter {
display:none;
}
<link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<input id="filter" type="text" />
<button id="btnTest">search</button>
<table id="ItemsTable" width="100%"></table>

Related

How can I in a DataTable pass the value of a target to a variable?

For example, in the following code I receive the records from a DB and I need to set the value of the targets: 1 to a variable to print it in other areas of the screen.
tableRefacciones = $('#lstRefacciones').DataTable({
dom: 'Bfrtip',
ajax: {
url: 'almacenes/salidas_caja_detalle.ajax.php',
dataSrc: ""
},
columnDefs: [
{
targets: 1,
visible: false
},
{
targets: 3,
visible: true,
render: $.fn.dataTable.render.number(',', '.', 2, '')
},
{
targets: 4,
visible: false,
}
I need to set the value of the targets: 1 to a variable to print it in other areas of the screen.

Colvis doesnt show any of the columns

schedule_Open_Datatable = $("#make_schedule_open_table").DataTable({
columnDefs: [
{ className: "control", orderable: false, targets: 1, width: "5%" },
{ orderable: false, targets: [2, 3, 4, 5, 6, 7, 8, 9, 10, 11] }
],
responsive: {
details: {
type: "column",
target: 1,
},
},
//scrollX: true,
buttons: ["copy", "csv", "excel", "pdf", "print", "colvis"],
sPaginationType: "full_numbers",
ajax: {
url: SODUrl,
// our data is an array of objects, in the root node instead of /data node, so we need 'dataSrc' parameter
dataSrc: "",
},
columns: columns,
rowReorder: { dataSrc: "seq" },
order: [[0, 'asc']],
dom: "<'row'<'col-sm-6'B><'col-sm-6'f>>" +
"<'row'<'col-sm-12'tr>>" +
"<'row'<'col-sm-4'l><'col-sm-4'i><'col-sm-4'p>>",
select: "single",
//ordering: false,
createdRow: function (row, data, dataIndex) {
$(row).attr("data-id", data.id);
},
The colvis button exists on the page but it doesn't want to show the column any of the columns , i have all the links that was required , i tried using the example used on the bootstrap 4 page but still doesnt work.

Show "All" pages in DataTables along with responsive tables and other attributes

I dont know how to to merge the function of my current attibutes of responsive and fixed header etc with Show "All" list function like it has in this one https://datatables.net/examples/advanced_init/length_menu.html
I dont know how to do it pls help here is my current function
<script type="text/javascript" language="javascript" class="init">
$(document).ready(function() {
var table = $('#example').DataTable({
responsive: true,
paging: false,
columnDefs: [{
searchable: false,
orderable: false,
targets: 0,
}],
order: [
[1, 'asc']
],
});
new $.fn.dataTable.FixedHeader(table);
table.on('order.dt search.dt', function() {
table.column(0, {
search: 'applied',
order: 'applied'
}).nodes().each(function(cell, i) {
cell.innerHTML = i + 1;
});
}).draw();
});
</script>
i am unable to merge the function with show "All" page length menu in javascript please help.
also please allow me run snippet im very new to js
thank you
var table = $('#example').DataTable({
responsive: true,
paging: false,
// Add this line
lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
columnDefs: [{
searchable: false,
orderable: false,
targets: 0,
}],
order: [
[1, 'asc']
],
});
new $.fn.dataTable.FixedHeader(table);

Data Table Row Undefined(DataTables.js)

I am trying to access the id of a row inside my DataTables application. When I select a particular row, the row gets selected, after that when I hit the edit button on a menu that I have displayed on the website the id of the row should get passed to a url(which I took off because it was not working so I decided to console.log the info)
The problem is that the row id is coming back as undefined even though I can visually inspect that the id is there.
Here is the code:
$(document).ready(function(){
var table = $('#example').DataTable({
responsive: true,
pagination: true,
serverSide: false,
processing: true,
dom: '<"pull-left"f><"pull-right"l>tip',
type: 'GET',
sAjaxSource:'EquipmentList/list.asp',
deferRender: true,
//idDisplayLength: 10,
select: true,
colspan: 7,
columns: [
{"data": "documento"},
{
"data": "fecha_entrada"
},
{"data": "numero_control"},
{"data": "nombre_cliente"},
{"data": "linea_contenedor"},
{"data": "estatus_actual"},
{"data":"estatus_actual"}
],
// add an id for each generated row:
fnCreatedRow: function(nRow, nData, nId) {
$(nRow).attr('id', nData['pk1']);
}
}); // end of datatable creation
$('#example tbody').on('click', 'tr', function() {
if ($(this).hasClass('selected')) {
$(this).removeClass('selected');
} else {
table.$('tr.selected').removeClass('selected');
$(this).addClass('selected');
}
});
$('#btnEdit').click(function () {
var selectedRow = table.row('.selected').id();
console.log(selectedRow);
});
});
For the selectedRow to show as undefined it must mean that the id is not being added to the datatable, but I know its there:
The id() method does not read the ID from the DOM. Instead of setting the id manually with the fnCreatedRow function use the rowId attribute. This sets the id Attribute in the DOM as well but also stores it internally for the use with the id() method.
So if you change the Datatables initialisation to something like this, your code works:
var table = $('#example').DataTable({
responsive: true,
pagination: true,
serverSide: false,
processing: true,
dom: '<"pull-left"f><"pull-right"l>tip',
type: 'GET',
sAjaxSource:'EquipmentList/list.asp',
deferRender: true,
//idDisplayLength: 10,
select: true,
colspan: 7,
rowId: "pk1",
columns: [
{"data": "documento"},
{"data": "fecha_entrada"},
{"data": "numero_control"},
{"data": "nombre_cliente"},
{"data": "linea_contenedor"},
{"data": "estatus_actual"},
{"data":"estatus_actual"}
]
}); // end of datatable creation
And below a working sample:
var table = $('#sample').DataTable({
serverSide: false,
searching: false,
rowId: "id",
data: [
{ "id": 5, "column-a": "Sample Data A", "column-b": 10, "column-c": "Lore ipsum" },
{ "id": 6, "column-a": "Sample Data B", "column-b": 5, "column-c": "Ipsum" },
{ "id": 8, "column-a": "Sample Data C", "column-b": 38, "column-c": "Lore" }
],
columnDefs: [
{
targets: 0,
data: "id",
title: "id"
},
{
targets: 1,
data: "column-a"
},
{
targets: 2,
data: "column-b"
},
{
targets: 3,
data: "column-c"
}
]
});
$('#sample tbody').on('click', 'tr', function() {
if ($(this).hasClass('selected')) {
$(this).removeClass('selected');
} else {
table.$('tr.selected').removeClass('selected');
$(this).addClass('selected');
}
});
$('#edit').click(function () {
var selectedRow = table.row('.selected').id();
alert(selectedRow);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<link href="https://cdn.datatables.net/1.10.15/css/jquery.dataTables.min.css" rel="stylesheet"/>
<button id="edit">Edit</button>
<table id="sample"></table>

DataTables - scrollX causing squashed header

So I'm using DataTables with the scrollX parameter set to true, however it's causing the thead columns to collapse.
Note: the datatable is appearing inside a Bootstrap Modal as part of a react project.
How can I resolve this?
When I click on one of the columns, causing it to refresh, it fixes itself. Also, if I remove the scrollX it also doesn't collapse.
Initialisation code:
$('#item-search').DataTable( {
ajax: {
"data": {
type: "map_items",
map_id: this.map_id
},
"dataSrc": (r) => {
console.log(r);
return r.data;
},
type: "POST",
url: "src/php/search.php"
},
autoWidth : false,
columns: [
{
"data": "brand"
},
{
"data": "name"
},
{
"data": "quantity"
},
{
"data": "measurement"
},
{
"data": "type"
},
],
dom: 'rtlip',
language: {
"info": "Showing page _PAGE_ of _PAGES_",
"infoFiltered": ""
},
lengthMenu: [ 1, 2, 3 ],
pageLength: 1,
processing: true,
responsive: true,
scrollX: true,
select: {
style: "multi"
},
serverSide: true
});
In data table initialization include following property.
autoWidth : true
Along with add this
"fnInitComplete": function(oSettings) {
$( window ).resize();
}
"fnDrawCallback": function(oSettings) {
$( window ).trigger('resize');
}
DataTable should be initialized with the following code to achieve horizontal scrolling:
"sScrollX": "100%",
"sScrollXInner": "110%",
"bScrollCollapse": true,
"fixedColumns": {
"leftColumns": 1
}
This work in my angular project
this.dtTarifas = {
scrollX: true,
autoWidth: false,
lengthChange: false,
responsive: false
}
I have in my package.json "angular-datatables": "7.0.0"
$('#DataTableID').DataTable({
//"scrollX": true,
"initComplete": function (settings, json) {
$("#DataTableID").wrap("<div style='overflow:auto; width:100%;position:relative;'></div>");
},
});

Categories

Resources