Datatable AJAX change on onClick - javascript

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.

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

Get row as object where checkbox is checked in datatable

i'm using datatable library and trying to get the entire row as object where checkbox "editado" is checked
I'm using the folowing code:
var a = $('#ContratoAlertaTabela').DataTable().rows(function (idx,
data, node) {
return $(node).find('.editado:input[type="checkbox"]').prop('checked');
}).data().toArray();
But it gives as object like:
0:
dataAssinatura: "2022-05-20T00:00:00"
dataTermino: "2022-05-13T00:00:00"
descricao: "Descrição 2021"
diasRestantes: -18
exercicio: 2021
fornecedor: "fornecedor 2"
id: 6
numero: "23452345"
tipo: "C"
visto: true
But i'm looking for this
0:
dataAssinatura: "2022-05-20T00:00:00"
dataTermino: "2022-05-13T00:00:00"
descricao: "Descrição 2021"
diasRestantes: -18
exercicio: 2021
fornecedor: "fornecedor 2"
id: 6
numero: "23452345"
tipo: "C"
visto: true
editado: true
And this is my datatable
var l = abp.localization.getResource('Contabilidade');
var dataTable = $('#ContratoAlertaTabela').DataTable(
abp.libs.datatables.normalizeConfiguration({
serverSide: true,
paging: true,
'order': [[2, 'asc']],
//order: false, //[[0, "asc"]],
searching: true,
scrollX: true,
ajax: abp.libs.datatables.createAjax(gcaspp.contabilidade.contratoAlerta.contratoAlerta.getListAlerta,
() => {
var visto = $("#ExibirVisto").is(":checked") ? "" : "true";
return { visto: visto };
}),
dom: '<"toolbar">',
columnDefs: [
{
title: 'Visto',
data: "visto",
orderable: false,
render: function (data) {
if (data) {
return '<input type="checkbox" name="cbox1" value="" checked>';
} else {
return '<input type="checkbox" name="cbox1" value="" >';
}
}
},
{
title: 'Editado',
render: function (data) {
return '<input type="checkbox" class="editado" name="teste" value="" >';
}
},
{
title: "visto",
data: "visto"
},
{
title: "id",
data: "id"
},
{
title: 'Tipo',
data: "tipo"
},
{
title: 'Numero',
data: "numero"
},
{
title: 'Exercicio',
data: "exercicio"
},
{
title: 'Descricao',
data: "descricao"
},
{
title: 'Fornecedor',
data: "fornecedor"
},
{
title: 'DataAssinatura',
data: "dataAssinatura"
},
{
title: 'DataTermino',
data: "dataTermino"
},
{
title: 'DiasRestantes',
data: "diasRestantes"
}
]
})
);
Any ideia about what i can do?

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 ?

Issue with Datatable and JSON calculation

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

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" }
],

Categories