number of index data each row in datatable - javascript

I want to create and show number sort ascending data in datatables like in this picture
index number
and I don't have sorted data number in database and my json data
this is my code:
$(document).ready(function() {
$('#dataya').DataTable({
lengthChange: false,
ajax: {
url: "http://localhost/jdih_webservice/api/xxxx",
dataSrc: ""
},
columns: [
{ data: "id_dokumen"},
{ data: "judul"},
{ data: "subjek"}
],
select: true
});
$('#search').click(function(){
var start_date = $('#start_date').val();
var end_date = $('#end_date').val();
var myTable = $('#dataya').DataTable({
"paging": true,
"lengthChange": true,
"searching": true,
"ordering": true,
"info": true,
"bDestroy": true,
"autoWidth": true,
"data": [],
"columns": [{
"title": "ID",
"data": "id_dokumen"
}, {
"title": "Judul",
"data": "judul"
}, {
"title": "Subjek",
"data": "subjek"
}],
"order": [[ 1, 'asc' ]]
});
if(start_date != '' && end_date !='')
{
var startDate = new Date(start_date);
var tglmulai = startDate.getFullYear();
var endDate = new Date(end_date);
var tglselesai = endDate.getFullYear();
let url = 'http://localhost/jdih_webservice/api/xxxx';
fetch(url)
.then(res => res.json())
.then((out) => {
var resultProductData = out.filter(function(a) {
var createdAt = new Date(a.tgltetap);
var tgldata = createdAt.getFullYear();
if( tgldata >= tglmulai && tgldata <= tglselesai ) return a;
});
myTable.clear();
$.each(resultProductData, function (index, value) {
myTable.row.add(value);
});
myTable.draw();
})
.catch(err => { throw err });
}
});
});
Anyone could help? , so appreciate thanks
and maybe if you not busy could you create/build in jsfiddle

This code is from this DataTables thread and should do what you want. It's using an additional column for the indexes:
dataTable.on( 'order.dt search.dt', function () {
dataTable.column(0, {search:'applied', order:'applied'}).nodes().each( function (cell, i) {
cell.innerHTML = i+1;
} );
} ).draw();

Related

Row-Reorder Function Calling Ajax Multiple Time to Save in Database

I have datatable Like this
oInnerTable = $("#url_table_" + rotator_id).DataTable({
"processing": true,
"serverSide": true,
rowReorder: {
dataSrc: [1]
},
"ajax":{
url :"actions/data_url_response.php",
type: "post",
data: function ( d ) {
var url_status = $('.url_status').val();
d.rotator_id = rotator_id;
d.url_status = url_status;
}
},
autoWidth: false,
columnDefs: [
{ "visible": false, "targets": 0 },
{ orderable: true, className: 'reorder', targets: 0 },
{
"targets":[0, 7],
"orderable":false,
},
{
targets: 0,
render: function (data, type, row) {
return '<div class="form-check"><input type="checkbox" class="form-check-input position-static select_ids" value="'+row[0]+'"></div>';
}
},
],
dom: '<"datatable-scroll"t><"datatable-footer"ip>',
language: {
search: '<span>Filter:</span> _INPUT_',
searchPlaceholder: 'Type to search...',
lengthMenu: '<span>Show:</span> _MENU_',
paginate: { 'first': 'First', 'last': 'Last', 'next': $('html').attr('dir') == 'rtl' ? '←' : '→', 'previous': $('html').attr('dir') == 'rtl' ? '→' : '←' }
}
});
And Update function is like below
var positionArray = [];
oInnerTable.on( 'row-reorder', function ( e, diff, edit ) {
for ( var i=0, ien=diff.length ; i<ien ; i++ ) {
var rowData = oInnerTable.row( diff[i].node ).data();
positionArray.push({
myid:rowData[0],
mypositiion: diff[i].newData
});
}
if (positionArray.length>0) {
$.post("/link-to-script.php", {
positionArray: positionArray
}, function(data, status) {
positionArray = [];
})
} ;
} );
Since I have three rows in table, everytime when I change position, its calling ajax three time and sometime its even more time, Its not possible that its fire only one time and I can send position data to server with single ajax call?
Thanks!

API in javascript is returning data, but is not being saved into an array

I am trying to fetch data from an API of WordPress.
Here is my code:
column.data().unique().sort().each(function (d,j) {
var practiceArea = d.practice_area;
var jsonPacticeArea = JSON.stringify(practiceArea);
if (jsonPacticeArea !== undefined) {
var res = $.map(jsonPacticeArea.split("|"), $.trim);
for (var i = 0; i < res.length; i++) {
var str = res[i];
str = str.replace(/"/gi, '').trim();
if (arrayPracticeArea.indexOf(str) === -1) {
arrayPracticeArea.push(str);
}
}
}
});
the "column" is the variable that is getting data through an API, and as far as I do console.log(column. data().unique().sort()), that's returning complete data as you can see in the screenshot and I want to fetch data is marked in red rectangle and store those values in an array, but as soon as I try to add "each" function to fetch the data and store it in an array (in my case its arrayPracticeArea) its returning undefined values.
Can anyone please help me out? I am just not much experienced with Javascript API.
Here is my AJAX code:
var tableAttorney = $('#table_affliate_attorney').DataTable({
destroy: true,
searching: true,
bLengthChange: false,
scrollX: true,
scrollY: 440,
autoWidth: false,
"language": {
"emptyTable": "We are sorry but there are no Affiliate Attorneys within a 150 mile radius of your requested search"
},
ajax: {
type: 'get',
url: "/wp-admin/admin-ajax.php",
dataType: 'json',
cache: false,
data: {
'action': 'get_attorney_ajax',
'center_lat': center_lat,
'center_long': center_long,
'state': state,
'city': city,
'zip': zip
}
},
columns: [
{"data": "title"},
{"data": "city"},
{"data": "state"},
{"data": "zip"},
{"data": "distance"},
{
"data": "phone",
className: 'datatablePhone',
render: function (data) {
return '' + data + '';
}
},
{
"data": "email",
className: 'px190EM',
render: function (data) {
return '' + data + '';
}
},
{
className: 'js-practice-area',
"data": "practice_area"
},
{
"targets": -1,
"data": 'email',
render: function (data) {
return "<a class='contact-lawyer' href='#' data-toggle='modal' data-target='#exampleModal' data-whatever='#mdo' data-email='"+data+"'>Contact</a>";
}
},
],
columnDefs: [
{"width": "150px", "targets": [0]},
{"width": "130px", "targets": [5]}
],
So I am trying to fetch data from columns->data that has value practice_area

Initialise same datatable with two functions

I have two functions (load_data and fetch_data) inside of my datatables script. They are both using different ajax calls.
My table (name: product_data) and the script is working as expected but this error message is shown with the first page load:
"DataTables warning: table id=product_data - Cannot reinitialise
DataTable"
I think this error comes because I have a mistake in mergin these two functions together in one script. Could you help me how the two functions can initialise my table "product_data" correctly ?
$(document).ready(function() {
// Start Function 1
load_data();
function load_data(is_category) {
var dataTable = $('#product_data').DataTable({
"processing": true,
"serverSide": true,
"sDom": "rtipl",
"order": [],
"ajax": {
url: "fetch.php",
type: "POST",
data: {
is_category: is_category
}
},
"columnDefs": [{
"targets": [2],
"orderable": false,
}, ],
});
}
// Script for Function 1 //
$(document).on('change', '#category', function() {
var category = $(this).val();
$('#product_data').DataTable().destroy();
if (category != '') {
load_data(category);
} else {
load_data();
}
});
// Start Function 2
fetch_data('no');
function fetch_data(is_date_search, start_date = '', end_date = '') {
var dataTable = $('#product_data').DataTable({
"processing": true,
"serverSide": true,
"order": [],
"ajax": {
url: "fetch.php",
type: "POST",
data: {
is_date_search: is_date_search,
start_date: start_date,
end_date: end_date
}
}
});
}
// Script for Function 2 //
$('#search').click(function() {
var start_date = $('#start_date').val();
var end_date = $('#end_date').val();
if (start_date != '' && end_date != '') {
$('#product_data').DataTable().destroy();
fetch_data('yes', start_date, end_date);
} else {
alert("Both Date is Required");
}
});
// Search Field
var datatable = $('#product_data').DataTable();
$('#searchfield').on('keyup', function() {
datatable.search(this.value).draw();
});
});
part of fetch.php
...
if($_POST["is_date_search"] == "yes")
{
$query .= 'order_id BETWEEN "'.$_POST["start_date"].'" AND "'.$_POST["end_date"].'" AND ';
}
if(isset($_POST["is_category"]))
{
$query .= "order_item = '".$_POST["is_category"]."' AND ";
}
...
At the backebd i,e fetch.php you may have validations
like check if start_date,end_date exist or not
check if is_category exist or not and fetch only for valid post data
$(document).ready(function() {
// Start Function 1
function load_data() {
//first recive all inputs here
let is_category = $("#category").val();
let start_date = $('#start_date').val();
let end_date = $('#end_date').val();
//at the backebd i,e fetch.php you may have validations
//i.e start_date,end_date exist or not
//is_category exist or not
//and initialise datatables once only
var dataTable = $('#product_data').DataTable({
"processing": true,
"serverSide": true,
"sDom": "rtipl",
"order": [],
"ajax": {
url: "fetch.php",
type: "POST",
data: {
is_category: is_category,
start_date: start_date,
end_date: end_date
}
},
"columnDefs": [{
"targets": [2],
"orderable": false,
}, ],
});
}
//calling the function on document load
load_data();
$(document).on('change', '#category', function() {
$('#product_data').DataTable().destroy();
load_data();
});
$('#search').click(function() {
if (start_date != '' && end_date != '') {
$('#product_data').DataTable().destroy();
load_data();
} else {
alert("Both Date is Required");
}
});
// Search Field
var datatable = $('#product_data').DataTable();
$('#searchfield').on('keyup', function() {
datatable.search(this.value).draw();
});
})

How to use multi column filter in jquery datatables

I am using Jquery datatables to export my file into excel from sql database. I have 3 column filtrers on my datatables which are working fine independently. I want them to work with or condition in a way that it gets all the data from the datatable where any one the conditions in the filters is met. below is my sample of code.
$(document).ready(function () {
var table = $('#studentTable').DataTable({
"ajax": {
"url": "/StructuredImportTgts/GetData",
"type": "GET",
"datatype": "json"
},
responsive: 'true',
dom: 'Bfrtip',
buttons: [
'copy', 'excel', 'pdf'
],
"columns": [
{ "data": "PART_NO" },
{ "data": "LEVEL" },
{ "data": "PART_NO" },
{ "data": "PART_NAME" },
{ "data": "L1QTY" },
{ "data": "PL1" },
{ "data": "PL2" },
{ "data": "PL3" },
{ "data": "SupplierLocID" },
{ "data": "SupplierLocID" },
{ "data": "Discrepancies" },
{ "data": "Comments" }
],
initComplete: function () { // After DataTable initialized
this.api().columns([1, 5, 6]).every(function () {
/* use of [1,2,3] for second, third and fourth column. Leave blank - columns() - for all.
Multiples? Use columns[0,1]) for first and second, e.g. */
var column = this;
var select = $('<select><option value=""/></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>')
});
}); // this.api function
} //initComplete function
});
});
For someone who is stuck in the similar problem, here is how I tackle it.
$(document).ready(function () {
$('#studentTable').DataTable({
"ajax": {
"url": "/StructuredImportTgts/GetData1",
"type": "GET",
"datatype": "json"
},
dom: 'Bfrtip',
buttons: [
'copy', 'excel', 'pdf'
],
"columns": [
//{ "data": "PART_NO" },
{ "data": "LEVEL" },
{ "data": "PART_NO" },
{ "data": "PART_NAME" },
{ "data": "L1QTY" },
{ "data": "PL1" },
{ "data": "PL2" },
{ "data": "PL3" },
{ "data": "SupplierLocID" },
//{ "data": "SupplierLocID" },
{ "data": "Discrepancies" },
{ "data": "Comments" }
],
initComplete: function () {
this.api().columns([4,5,6]).every(function () {
var column = this;
var select = $('<select><option value=""></option></select>')
.appendTo($(column.footer()).empty())
.on('change', function () {
$('#studentTable').DataTable().draw();
});
column.data().unique().sort().each(function (d, j) {
select.append('<option value="' + d + '">' + d + '</option>')
});
});
}
});
});
$.fn.dataTable.ext.search.push(
function (settings, searchData, index, rowData, counter) {
if (settings.nTable.id !== 'studentTable') {
return true;
}
var position = $("#position option:selected").text();
var office = $("#office option:selected").text();
var off = $("#off option:selected").text();
// Display the row if both inputs are empty
if (position.length === 0 && office.length === 0 && off.length === 0) {
return true;
}
// Display row if position matches position selection
hasPosition = true;
if (position !== searchData[4]) {
hasPosition = false; //Doesn't match - don't display
}
// Display the row if office matches the office selection
hasOffice = true;
if (office !== searchData[5]) {
hasOffice = false; //Doesn't match - don't display
}
hasOff = true;
if (off !== searchData[6]) {
hasOff = false; //Doesn't match - don't display
}
// If either position or office matched then display the row
return true ? hasPosition || hasOffice || hasOff : false;
});

Add a Count for each button using Data Tables

I am using data tables. Currently, it is working as expected, hower I would like to have the Add and Remove Buttons have some sort of count. For example AddButton_0
How would I do this using Data Tables?
var url = "/ClientSetup/GetCatalogueContracts";
var contractsTable = $('#catalogueContractsTable').DataTable({
sAjaxSource: url,
columns: [
{ "data": "ID" },
{ "data": "Selected"},
{ "data": "Name"},
{ "data": "ContractType"},
{ "data": "StartDate"},
{ "data": "TerminationDate"},
{ "button": "Action" }
],
serverSide: true,
sDom: 't<"dt-panelfooter clearfix"ip>',
pageLength: pageSize,
bSort: false,
bLengthChange: false,
bSearch: true,
paging: true,
searching: true,
order: [[2, "asc"]],
language: {
emptyTable: "No contracts found.",
zeroRecords: "No contracts found.",
info: "_START_ to _END_ of _TOTAL_",
paginate: {
first: "First",
previous: "Previous",
next: "Next",
last: "Last"
}
},
columnDefs: [
{
targets: [0],
visible: false
},
{
targets: [1],
visible: false
},
{
targets: [2]
},
{
targets: [3],
sClass: "hidden-xs hidden-sm contractType"
},
{
targets: [4],
sClass: "hidden-xs fromDate"
},
{
targets: [5],
sClass: "hidden-xs terminationDate"
},
{
data: null,
targets: [6],
sClass: "updateTableRow text-center",
render: function ( data, type, full, meta )
{
var id = data["ID"];
return `<button class=\"btn btn-success br2 btn-xs fs12 table-btn button-selector-${id}\" id=\"AddContractBtn\">Add</button>`;
}
}
],
drawCallback: function( settings ) {
disableInvalidContracts();
},
autoWidth: false
});
// make sure already selected rows cannot be added again.
var excludeIds = getExcludeIds();
$.each(excludeIds, function() {
var button = $("#AddContractBtn.button-selector-" + this);
button.addClass("disabled");
button.prop('disabled', true);
});
}
#* Adding and Removing Data from both Tables *#
contractsTable.on('click', '#AddContractBtn', function () {
var $row = $(this).closest("tr");
#*Track Contract IDs that have been removed from the unselected table*#
var value = $('#exclude-ids').val();
var ids = getExcludeIds();
ids.push($row.attr('id'));
$('#exclude-ids').val(JSON.stringify(ids));
var addRow = contractsTable.row($row);
var data = addRow.data();
data.Selected = true;
selectedContractsTable.row.add(addRow.data()).draw( false );
setSelectedInputForContract('true', data.ID);
disableInvalidContracts();
});
selectedContractsTable.on('click', '#RemoveContractBtn', function () {
var $row = $(this).closest('tr');
var addRow = selectedContractsTable.row($row);
var data = addRow.data();
data.Selected = false;
addRow.data(data);
addRow.remove().draw();
#* Remove the Contract ID from the exclide ids hidden input*#
var value = $('#exclude-ids').val();
var ids = getExcludeIds();
ids = ids.filter(i => i !== $row.attr('id'));
$('#exclude-ids').val(JSON.stringify(ids));
setSelectedInputForContract('false', data.ID);
disableInvalidContracts();
});
I am looking for a way that I can add a Count for each of the buttons for example `AddButton_0 I am unsure if there is an option to use a count on DataTables. Or whether I could use JQuery?
Try this : you can have global variable and increment it for each access of button creation function. Click handler for add and remove button can be created with start with attribute selector in jquery.
See below code
var count = 0;
var url = "/ClientSetup/GetCatalogueContracts";
var contractsTable = $('#catalogueContractsTable').DataTable({
sAjaxSource: url,
columns: [
{ "data": "ID" },
{ "data": "Selected"},
{ "data": "Name"},
{ "data": "ContractType"},
{ "data": "StartDate"},
{ "data": "TerminationDate"},
{ "button": "Action" }
],
serverSide: true,
sDom: 't<"dt-panelfooter clearfix"ip>',
pageLength: pageSize,
bSort: false,
bLengthChange: false,
bSearch: true,
paging: true,
searching: true,
order: [[2, "asc"]],
language: {
emptyTable: "No contracts found.",
zeroRecords: "No contracts found.",
info: "_START_ to _END_ of _TOTAL_",
paginate: {
first: "First",
previous: "Previous",
next: "Next",
last: "Last"
}
},
columnDefs: [
{
targets: [0],
visible: false
},
{
targets: [1],
visible: false
},
{
targets: [2]
},
{
targets: [3],
sClass: "hidden-xs hidden-sm contractType"
},
{
targets: [4],
sClass: "hidden-xs fromDate"
},
{
targets: [5],
sClass: "hidden-xs terminationDate"
},
{
data: null,
targets: [6],
sClass: "updateTableRow text-center",
render: function ( data, type, full, meta )
{
var button = `<button class=\"btn btn-success br2 btn-xs fs12 table-btn button-selector-${id}\" id=\"AddContractBtn' + count + '\">Add</button>`;
count++; // increment count
var id = data["ID"];
return button;
}
}
],
drawCallback: function( settings ) {
disableInvalidContracts();
},
autoWidth: false
});
// make sure already selected rows cannot be added again.
var excludeIds = getExcludeIds();
$.each(excludeIds, function() {
var button = $("#AddContractBtn.button-selector-" + this);
button.addClass("disabled");
button.prop('disabled', true);
});
}
#* Adding and Removing Data from both Tables *#
contractsTable.on('click', 'button[id^=AddContractBtn]', function () {
var $row = $(this).closest("tr");
#*Track Contract IDs that have been removed from the unselected table*#
var value = $('#exclude-ids').val();
var ids = getExcludeIds();
ids.push($row.attr('id'));
$('#exclude-ids').val(JSON.stringify(ids));
var addRow = contractsTable.row($row);
var data = addRow.data();
data.Selected = true;
selectedContractsTable.row.add(addRow.data()).draw( false );
setSelectedInputForContract('true', data.ID);
disableInvalidContracts();
});
selectedContractsTable.on('click', 'button[id^=RemoveContractBtn]', function () {
var $row = $(this).closest('tr');
var addRow = selectedContractsTable.row($row);
var data = addRow.data();
data.Selected = false;
addRow.data(data);
addRow.remove().draw();
#* Remove the Contract ID from the exclide ids hidden input*#
var value = $('#exclude-ids').val();
var ids = getExcludeIds();
ids = ids.filter(i => i !== $row.attr('id'));
$('#exclude-ids').val(JSON.stringify(ids));
setSelectedInputForContract('false', data.ID);
disableInvalidContracts();
});

Categories