Issue with Datatable and JSON calculation - javascript

I am using datatable, loading data from ajax and preforming operation with javacript.
var table = $('#example').DataTable({
"ajax": {
"url": apiurl,
"type": 'GET',
"datatype": 'json'
},
// data: dataSet,
columns: [
{ title: "Item Key", data: "itemKey" },
{ title: "Description", data: "description" },
{ title: "Pounds", data: "pound" },
{
title: "Current Cost", data: function (data, type, row) {
return '<input type="number" class ="price-input" value="' + data.cost + '" style="background-color:lightgoldenrodyellow;">';
}
},
{ title: "Current Cost", data: "cost" },
{ title: "Unit", data: "unit" },
{
title: "Quantity", data: "quantity"
},
{
title: "Total", data: function (data, type, row) {
return data.cost * data.quantity;
}
},
{
title: "New Total", "data": "total",
"render": function (data, type, row) {
return "$" + data;
}
}
],
});
function calcTotal(q, p) {
var t = 0.00;
t = parseInt(q) * parseFloat(p);
return t.toFixed(2);
}
var table = $('#example').DataTable();
$.each(table, function (i, r) {
r.total = calcTotal(r.qty, r.price);
});
$("#example").on("change", ".price-input", function (event) {
var row = $(this).closest("tr");
var qty = table.cell($("td", row).eq(6)).data();
var price = $(this).val();
var total = table.cell($("td", row).eq(8).get(0));
total.data(calcTotal(qty, price)).draw();
});
'''
My problem is in the last column, when the datatable loads, value appear as undefined, when I change the value in textbox I am getting the right result and number How Can I able to see right number when Datatable loads? Please guide me

Related

how to add a href route with parameter in datatable

here is i have a datatable based table i have fetched a data from database and displayed using datatable but in this datatable i went to redirect to show for each row of datatable so how to add a route for show with parameter 1d for each row thanks and waiting a positive response!
here is my code
<script>
$(function() {
$("#start_date").datepicker({
"dateFormat": "yy-mm-dd"
});
$("#end_date").datepicker({
"dateFormat": "yy-mm-dd"
});
});
// Fetch records
function fetch(start_date, end_date,zone_id,status_id,sector_id) {
$.ajax({
url: "{{ route('ProjectFilterdate/records') }}",
type: "GEt",
data: {
start_date: start_date,
end_date: end_date,
zone_id:zone_id,
status_id:status_id,
sector_id:sector_id
},
dataType: "json",
success: function(data) {
// Datatables
var i = 1;
$('#records').DataTable({
"data": data.ptojects,
// buttons
"dom": "<'row'<'col-sm-12 col-md-4'l><'col-sm-12 col-md-4'B><'col-sm-12 col-md-4'f>>" +
"<'row'<'col-sm-12'tr>>" +
"<'row'<'col-sm-12 col-md-5'i><'col-sm-12 col-md-7'p>>",
"buttons": [
'copy','excel', 'pdf', 'print'
],
// responsive
"responsive": true,
"columns": [{
"data": "id",
"render": function(data, type, row, meta) {
return i++;
}
},
{
"data": "code"
},
{
"data": "name"
},
{
"data": "proposal_date"
},
{
"data": "proposal_value"
},
{
"data": "contractor"
},
{
"data": "subcontractor"
},
{
render: function ( data, type, row) {
return 'test';
}
},
]
});
}
});
}
i am trying to make an a href route but i don't know how to add an id parameter
here is the link i am trying
{
render: function ( data, type, row) {
return 'test';
}
the place of 1 must be replaced by id for each row
This is how i did t :
return DataTables::of($data)->addIndexColumn()
->addColumn('project', function ($test) {
return $test->project->title;
})
->addColumn('action', function ($test) {
$result = $test->active ? 'btn-success' : 'btn-danger';
return '<a href="' . route('projectDetail', [
'id' => $test->id
]) . '">detail </a>
';
})
->rawColumns([
'action'
])
->make(true);
}

How to get all ID's of all Checked data in all pages on Datatables

Hi i have my datatables with checkbox at the first column
i able to get the checked checkbox id but i cannot get all the data on the other page
i have this to render my datatables
var tableDelcar;
function LoadTableDelcar() {
tableDelcar = $('#tblDelcar').DataTable({
//dom: 'Brtip',
order: [[1, 'asc']],
buttons: [
'csv', 'excel', 'pdf', 'print'
],
pageLength: 10,
"ajax": {
async: false,
type: 'POST',
contentType: 'application/json',
url: 'MaintenancePage.aspx/getCarDelMaintable',
"dataSrc": "d",
dataType: 'json',
},
"columns": [
{
"d": null,
render: function (data, type, row, meta) {
return '<input type="checkbox" class="select" id="' + row.CAR_NO + '"></td>';
}, title: "Action"
},
{ "data": "CAR_NO", title: "Car No" },
{ "data": "FINDINGS", title: "FINDINGS" },
{ "data": "ActionOwner", title: "Action Owner" },
{ "data": "Auditor", title: "Status" },
{ "data": "COORDINATOR", title: "COORDINATOR" }
]
});
}
and this is my function on getting the ID's of the checked checkboxes
function DeleteCar() {
var IDs = $("#tblDelcar input:checkbox:checked").map(function () {
return $(this).attr("id");
}).get(); alert(IDs);
}
Make sure your DOM is loaded when you call your function in the other page.
you have error ?

Datatable AJAX change on onClick

Hello my Datatable ajax works on first onClick event but getting error after that
warning: table id=example - Cannot reinitialise DataTable. For more information about this error, please see http://datatables.net/tn/3
This is my code
<table id="example" class="display dataTable cell-border table table-striped table-bordered" data-page-length='25' style="width:100%"> </table>
<select class="form-control" style=" background-color:lightgoldenrodyellow;" asp-items="#(new SelectList(string.Empty, "code", "productName"))" id="formulaId"></select>
$("#formulaId").change(function () {
var popup, dataTable;
var entity = 'Quote';
var apiurl = '/api/' + entity + '/index';
var formulaId = $('#formulaId').val();
alert(formulaId);
var table = $('#example').DataTable({
"ajax": {
destroy: true,
retrieve: true,
paging: false,
searching: false,
"url": apiurl + '/' + formulaId,
"type": 'GET',
"datatype": 'json'
},
// data: dataSet,
columns: [
{ title: "Item Key", data: "itemKey" },
{ title: "Description", data: "description" },
{ title: "Pounds", data: "pound" },
{ title: "Current Cost", data: "cost" },
{
title: "New Cost", data: "cost",
"render": function (data, type, row) {
return '<input type="number" class ="price-input" value="' + data + '" style="background-color:lightgoldenrodyellow;">';
}
},
{ title: "Unit", data: "unit" },
{
title: "Quantity", data: "quantity"
},
{
title: "Total", data: function (data, type, row) {
return '<input type="number" readonly value="' + data.totalCost + '" style="background-color:lightgoldenrodyellow;">';
}
},
{
title: "New Total", "data": "totalCost",
"render": function (data, type, row) {
return '<input type="number" readonly class ="price-input" value="' + data + '" style="background-color:lightgoldenrodyellow;">';
}
}
],
My question is it was working for first time, even for the second time I am getting formulaId in alert but after that I am getting warning for dataTable. Please guide me.

datatable editor Unable to automatically determine field from source

Having some problems in getting the editor of datatable to start working. keep getting the error Unable to automatically determine field from source. In my particular case the table is already loaded in html and on edit have to send the edited field to the server. Using inline edit functionality of the editor. Code for the initialization of datatable and editor is as follows
var ajaxBase = {
dataType: "json",
contentType: "application/json; charset=utf-8",
processData: "false",
headers: { "X-CSRFToken": '{{ csrf_token }}' },
data: function ( d ) {
console.log(d)
return JSON.stringify(d)
}
};
var editor = new $.fn.dataTable.Editor( {
table: "#response",
fields: [
{
name: "shop-name",
data:"shop-name"
},
{
name: "title"
},
{
name: "price"
},
{
name: "details",
}
]
} );
$('#response').on( 'click', 'tbody td:not(:first-child, :nth-child(3), :nth-child(7), :nth-child(8))', function (e) {
editor.inline(this);
} );
var table = $('#response').DataTable( {
fixedHeader: true,
responsive:true,
columns: [
{ "name": "group" },
{ "name": "shop-name" },
{ "name": "Thumbnail" },
{ "name": "title" },
{ "name": "price" },
{ "name": "details" },
{ "name": "url" },
{ "name": "manage" }
],
columnDefs: [{
render: function (data, type, full, meta) {
if (data.length<100){
return "<div class='text-wrap width-200'>" + data +"</div>";
}
return "<div class='text-wrap width-200'><div>" + data.slice(0,100) + "<a style='cursor:pointer;font-weight:bold;' onclick='show(this)'>...Show More</a></div><div style='display:none;'>"+data+" <a style='cursor:pointer;font-weight:bold;' onclick='hide(this)'>Show Less</a></div></div>";
},
targets: [5]
},
{
render: function (data, type, full, meta) {
return "<div align='center' class='text-wrap width-20'>" + data+"</div>"
},
targets: [0,1,3,4]
},
{
render: function (data, type, full, meta) {
return "<div align='center'><a style='cursor:pointer;color:blue;' href='"+data+"'>Open</a></div>"
},
targets: [6]
},
{
render: function (data, type, full, meta) {
return "<div align='center'><img src='" + data+"' width='60px' height='60px'></img></div>"
},
targets: [2]
},
],
} );
1- Ensure that the fields in your "editor" are completely matching with the columns specified in $('#response').DataTable( ... )
2- Use data keyword instead of name while specifying the columns.
fields: [
{
name: "group",
data:"group"
},
{
name: "shop-name",
data:"shopname"
},
{
name: "Thumbnail",
data:"thumbnail"
},
{
name: "Title",
data:"title"
},
{
name: "Price",
data:"price"
},
{
name: "Details",
data:"details"
},
{
name: "URL",
data:"url"
},
{
name: "Manage",
data:"manage"
}
]
...
columns: [
{ data: "group" },
{ data: "shopname" },
{ data: "thumbnail" },
{ data: "title" },
{ data: "price" },
{ data: "details" },
{ data: "url" },
{ data: "manage" }
],

Updating Div with Total Records Outside of table

I’m working with datatables and trying to figure out what I’m doing wrong. I am trying to display the total number of rows when the table hits the draw event on the table. Right now with the code, I’m showing below I am not getting any console errors. The element where the number is supposed to be updated is correct. I am just not getting it to render with the correct count.
("use strict");
const renderStatusCell = (data, type, full, meta) => {
const status = {
0: { title: "Inactive" },
1: { title: "Active" }
};
if (typeof status[data] === "undefined") {
return data;
}
return status[data].title;
};
var table = $('[data-table="users.index"]');
// begin first table
table.DataTable({
// Order settings
order: [[1, "desc"]],
ajax: "/titles",
columns: [
{ data: "id", title: "User ID" },
{ data: "name", title: "Name" },
{ data: "slug", title: "Slug" },
{ data: "introduced_at", title: "Date Introduced" },
{ data: "is_active", title: "Status", render: renderStatusCell },
{
data: "action",
title: "Actions",
orderable: false,
responsivePriority: -1
}
]
});
var updateTotal = function() {
table.on("draw", function() {
$("#kt_subheader_total").html(table.fnSettings().fnRecordsTotal());
});
};
I expected when the table was rendered to update the dom with the correct number of rows however the div does not get updated.
I don't understand your problem, but I think you need something like that.
table
.row($(this).parents('tr'))
.remove()
.draw();
or
table.ajax.reload();
I believe you need to wait until the HTML loads before running all your javascript code. Also, if you are storing the total, you not make it a function but rather just store the value.
'use strict';
// this will make sure all the HTML loads before the JavaScript runs.
$(function() {
var table = $('[data-table="users.index"]');
var updateTotal = null; // store in a variable
const renderStatusCell = (data, type, full, meta) => {
const status = {
0: { title: "Inactive" },
1: { title: "Active" }
};
if (typeof status[data] === "undefined")
return data;
return status[data].title;
};
// begin first table
table.DataTable({
// Order settings
order: [[1, "desc"]],
ajax: "/titles",
columns: [
{ data: "id", title: "User ID" },
{ data: "name", title: "Name" },
{ data: "slug", title: "Slug" },
{ data: "introduced_at", title: "Date Introduced" },
{ data: "is_active", title: "Status", render: renderStatusCell },
{
data: "action",
title: "Actions",
orderable: false,
responsivePriority: -1
}
]
});
table.on("draw", function() {
updateTotal = table.fnSettings().fnRecordsTotal();
$("#kt_subheader_total").html(table.fnSettings().fnRecordsTotal());
});
});

Categories