This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 1 year ago.
how i can read specific data from JSON file without element name, i working with datatables, the follow is de code, for example, i need read in javascript file only row value '2021-06-21' and '$8.000', how would can to get these value.
I working with JSON file generated for PHP and datatables
This is my JSON file format example:
{
"draw": 0,
"recordsTotal": null,
"recordsFiltered": null,
"data": [
[
"hola",
"1",
"Product",
"2021-06-21",
"$ 1.091.000\n",
"$ 8.000\n",
"$ 16.000\n",
"$ 1.115.000\n",
"$ 1.949.000\n",
"$ 834.000\n",
"76%",
"988980003697VO"
],
My JS code from datatable
function format ( data ) {
return '<table cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">'+
'<tr>'+
'<td>Full name:</td>'+
'<td>'+data.[6]+'</td>'+
'</tr>'+
'<tr>'+
'<td>Extension number:</td>'+
'<td>'+data.[11]+'</td>'+
'</tr>'+
'<tr>'+
'<td>Extra info:</td>'+
'<td>And any further details here (images etc)...</td>'+
'</tr>'+
'</table>';
}
$(document).ready(function(){
var employeeData = $('#escanmotorList').DataTable({
"lengthChange": true,
"processing":true,
"serverSide":true,
"autoWidth": false,
"order":[],
"ajax":{
url:"action.php",
type:"POST",
data:{action:'listEscanmotor'},
dataType:"json"
},
"language": {
"lengthMenu": "Mostrando _MENU_ productos por página",
"zeroRecords": "Nothing found - sorry",
"info": "Página _PAGE_ de _PAGES_",
"loadingRecords": "Cargando...",
"infoEmpty": "No records available",
"search": "Buscar",
"processing": "Procesando...",
"paginate": {
"first": "Primero",
"last": "Último",
"next": "Siguiente",
"previous": "Anterior"
},
"infoFiltered": "(filtered from _MAX_ total records)"
},
"columns": [
{ "width": "15px", "targets": 1, "className": 'details-control' },
{ "width": "15px", "targets": 1 },
null,
{ "width": "55px", "targets": 1 },
{ "width": "90px", "targets": 1 },
{ "width": "40px", "targets": 1 },
{ "width": "40px", "targets": 1 },
{ "width": "90px", "targets": 1 },
{ "width": "90px", "targets": 1, "orderable": false },
{ "width": "70px", "targets": 1 },
{ "width": "30px", "targets": 1, "orderable": false },
{ "width": "120px", "targets": 1, "orderable": false },
{ "width": "70px", "targets": 1 },
{ "width": "60px", "targets": 1, "orderable": false },
{ "width": "60px", "orderable": false },
{ "width": "60px", "orderable": false }
],
"pageLength": 10
});
$('#escanmotorList tbody').on('click', 'td.details-control', function () {
var tr = $(this).closest('tr');
var row = employeeData.row( tr );
if ( row.child.isShown() ) {
// This row is already open - close it
row.child.hide();
tr.find('svg').attr('data-icon', 'plus-circle'); // FontAwesome 5
}
else {
// Open this row
row.child( format(row.data()) ).show();
tr.find('svg').attr('data-icon', 'minus-circle'); // FontAwesome 5
}
} );
You access it not via "name", but via "key". And non-associative arrays has default keys from 0 to "length-1". In your case myJson.data[0][6]
var myJson = {
"draw": 0,
"recordsTotal": null,
"recordsFiltered": null,
"data": [
[
"hola",
"1",
"Product",
"2021-06-21",
"$ 1.091.000\n",
"$ 8.000\n",
"$ 16.000\n",
"$ 1.115.000\n",
"$ 1.949.000\n",
"$ 834.000\n",
"76%",
"988980003697VO"
],
]
};
console.log(
myJson.data[0][6],
myJson.data[0][11],
myJson.data[0][myJson.data[0].length - 1]
);
Related
I want to create a dynamic system for Datatables.
I have this code where I attribute to all elements with the class "my-datatable" the DataTable main options. Next I want to add options for a specific Datatable.
$(".my-datatable").DataTable({
responsive: true,
dom: 'Bfrtip',
buttons: [
'csv',
'excel',
'pdf',
],
"language": {
"search": "",
"searchPlaceholder": "Search for any client’s information…",
"emptyTable": "No data available in table",
"info": "",
"infoEmpty": "Showing 0 to 0 of 0 entries",
"infoFiltered": "(filtered from _MAX_ total entries)",
"lengthMenu": "Show _MENU_ entries",
"loadingRecords": "Loading...",
"processing": "Processing...",
"zeroRecords": "No matching records found",
},
});
$(".my-datatable#specific-datatable").DataTable({
"order": [[ 1, "asc" ]],
columnDefs: [
{ targets: [0,2,4,5,7], orderable: false },
],
"columns": [
{ "width": "5%" },
{ "width": "20%" },
{ "width": "10%" },
{ "width": "5%" },
{ "width": "20%" },
{ "width": "10%" },
{ "width": "15%" },
{ "width": "20%" },
]
});
$.extend can be applied in this case. After declaring the option of the first table, extend specific table property by the option using $.extend as following
var originalTableOption = {
responsive: true,
dom: 'Bfrtip',
buttons: [
'csv',
'excel',
'pdf',
],
"language": {
"search": "",
"searchPlaceholder": "Search for any client’s information…",
"emptyTable": "No data available in table",
"info": "",
"infoEmpty": "Showing 0 to 0 of 0 entries",
"infoFiltered": "(filtered from _MAX_ total entries)",
"lengthMenu": "Show _MENU_ entries",
"loadingRecords": "Loading...",
"processing": "Processing...",
"zeroRecords": "No matching records found",
},
};
$(".my-datatable").DataTable(originalTableOption);
var specificTableOnlyOption = {
"order": [[ 1, "asc" ]],
columnDefs: [
{ targets: [0,2,4,5,7], orderable: false },
],
"columns": [
{ "width": "5%" },
{ "width": "20%" },
{ "width": "10%" },
{ "width": "5%" },
{ "width": "20%" },
{ "width": "10%" },
{ "width": "15%" },
{ "width": "20%" },
]
};
var specificTableOption = $.extend(specificTableOnlyOption, originalTableOption);
$(".my-datatable#specific-datatable").DataTable(specificTableOption);
I'd like to know how change a cell value in Datatables.
I need to set the first cell of the last row with the value of rows.count().
Here's my function to create the Datatables :
function callForStepBoxes(){
flow.steps = [];
flowChartJSON = new Array();
if(!typeof currentFlowsTable === 'undefined' || currentFlowsTable != null){
$('#flowsTable').DataTable().ajax.url(restURI + 'orch/search/operations/'+flow.name).load();
$('#flowsTable').DataTable().ajax.reload();
} else {
currentFlowsTable = $('#flowsTable').DataTable({
responsive: true,
columnDefs: [
{ responsivePriority: 1, targets: 0 },
{ responsivePriority: 2, targets: 4 },
{ responsivePriority: 3, targets: 2 },
{ responsivePriority: 4, targets: 3 },
{ responsivePriority: 5, targets: 4 },
{ responsivePriority: 6, targets: 5 }
],
ajax: {
"url": restURI + 'orch/search/operations/'+flow.name,
"contentType": "application/json",
"type": "GET",
"data": null,
},
order: [0, 'desc'],
scrollCollapse: true,
scrollX: false,
aLengthMenu: [
[10, 25, 50, 100, -1],
[10, 25, 50, 100, "All"]
],
iDisplayLength: -1,
"columns": [
{"data": "ROWID", "defaultContent": "", "sClass": "displayNone"},
{"data": "STEP", "defaultContent": "", "sClass": "text-center limitedWidth"},
{"data": "OPERATION_NAME", "defaultContent": "", "sClass": "text-center limitedWidth"},
{"data": null, "defaultContent": "<input type='number' class='flowTimeoutValue'/>", "sClass": "text-center limitedWidth"},
{"data": null, "defaultContent": "<input type='number' class='flowLimitValue'/>", "sClass": "text-center limitedWidth"},
{"data": null, "defaultContent": "<input type='checkbox' class='flowActiveValue' checked='false'/>", "sClass": "text-center limitedWidth"},
],
'rowCallback': function(row, data, index) {
// Retrieve rows.count
lastStep = currentFlowsTable.data().count();
// Retrieve last row
lastRow = currentFlowsTable.row(':last').data();
// Set the value
lastRow.STEP = lastStep;
currentFlowsTable.row(':last').data().STEP = lastStep;
},
'drawCallback': function(settings){
createNodesAndEdges(flowChartJSON);
}
});
};
}
I retrieve the rows.count() value, I retrieve the last row and set the value but it does not work. What am I doing wrong ? Thank you !
can you please try below change.
var flowTable = $('#flowsTable').DataTable().ajax.url(restURI + 'orch/search/operations/'+flow.name).load();
flowTable.ajax.reload();
I've found the solution. I've add a class to the column I want to update the first cell then I check if the cell's value is empty or not.
function callForStepBoxes(){
flow.steps = [];
flowChartJSON = new Array();
if(!typeof currentFlowsTable === 'undefined' || currentFlowsTable != null){
var flowTable = $('#flowsTable').DataTable().ajax.url(restURI + 'orch/search/operations/'+flow.name).load();
flowTable.ajax.reload();
} else {
currentFlowsTable = $('#flowsTable').DataTable({
responsive: true,
columnDefs: [
{ responsivePriority: 1, targets: 0 },
{ responsivePriority: 2, targets: 4 },
{ responsivePriority: 3, targets: 2 },
{ responsivePriority: 4, targets: 3 },
{ responsivePriority: 5, targets: 4 },
{ responsivePriority: 6, targets: 5 }
],
ajax: {
"url": restURI + 'orch/search/operations/'+flow.name,
"contentType": "application/json",
"type": "GET",
"data": null,
},
order: [0, 'desc'],
scrollCollapse: true,
scrollX: false,
aLengthMenu: [
[10, 25, 50, 100, -1],
[10, 25, 50, 100, "All"]
],
iDisplayLength: -1,
"columns": [
{"data": "ROWID", "defaultContent": "", "sClass": "displayNone"},
{"data": "STEP", "defaultContent": "", "sClass": "text-center limitedWidth stepCell"},
{"data": "OPERATION_NAME", "defaultContent": "", "sClass": "text-center limitedWidth"},
{"data": null, "defaultContent": "<input type='number' class='flowTimeoutValue'/>", "sClass": "text-center limitedWidth"},
{"data": null, "defaultContent": "<input type='number' class='flowLimitValue'/>", "sClass": "text-center limitedWidth"},
{"data": null, "defaultContent": "<input type='checkbox' class='flowActiveValue' checked='false'/>", "sClass": "text-center limitedWidth"},
],
'rowCallback': function(row, data, index) {
// Set the STEP for ARCHIVE operation
lastStep = currentFlowsTable.data().count();
if($(row).find('.stepCell').text() === "") {
$(row).find('.stepCell').append(lastStep);
}
},
'drawCallback': function(settings){
createNodesAndEdges(flowChartJSON);
}
});
};
}
i have a dataTable with multi-column ordering and it works but I need:
first column "asc" and second column desc -> how is this possible?
here is my fiddle: https://jsfiddle.net/zukii/Lucq6vc5/28/
in this fiddle the column "Rating" is automatic default sorting "asc" and then the column "Price" should be automatic "desc"
var mytable = $('table.dt-tarif').dataTable({
"paging": false,
"info": false,
"searching": false,
"order": [[ 3, "desc" ]],
"aoColumnDefs": [
{
"bSortable": false,
"aTargets": [0]
},
{
"type": "currency", targets: 3
},
{
targets: [ 3 ],
orderData: [3, 4]
}
],
"language": {
"lengthMenu": "Zeige _MENU_",
"zeroRecords": "Keine Entwürfe vorhanden!",
"info": "Seite _PAGE_ von _PAGES_",
"infoEmpty": "Es konnte kein Entwurf gefunden werden.",
"infoFiltered": "",
"search": " ",
"paginate": {
"first": "Erste",
"last": "Letzte",
"next": "Vor",
"previous": "Zurück"
},
}
});
thanks and greetings ;)
You needs to use a 2D array to achieve multi-column sorting to archive the result.
var table = $('table.dataTable').DataTable();
table
.order( [ 3, 'asc' ],[ 4, 'desc' ] )
.draw();
further you can change the format [ columnIndex, "asc|desc" ] (e.g. [ 1, "desc" ] for sorting .
Solution fiddle: https://jsfiddle.net/ShirishDhotre/a3utn0ek/7/
Check if this help to close your issue.
This one is working perfect now :)
https://jsfiddle.net/zukii/Lucq6vc5/37/
jQuery.extend( jQuery.fn.dataTableExt.oSort, {
"currency-pre": function ( a ) {
a = (a==="-") ? 0 : a.replace( /[^\d\-\.]/g, "" );
return parseFloat( a );
},
"currency-asc": function ( a, b ) {
return a - b;
},
"currency-desc": function ( a, b ) {
return b - a;
}
} );
jQuery.extend( jQuery.fn.dataTableExt.oSort, {
"currency": function ( a ) {
var x = a.replace(",", ".").replace("€", "");
return parseFloat( x );
}});
var mytable = $('table.dt-tarif').dataTable({
"paging": false,
"info": false,
"searching": false,
"order": [[ 3, "desc" ]],
"aoColumnDefs": [
{
"bSortable": false,
"aTargets": [0]
},
{
"type": "currency", targets: 3
},
{
targets: [ 3 ],
orderData: [3, 4]
}
],
"language": {
"lengthMenu": "Zeige _MENU_",
"zeroRecords": "Keine Entwürfe vorhanden!",
"info": "Seite _PAGE_ von _PAGES_",
"infoEmpty": "Es konnte kein Entwurf gefunden werden.",
"infoFiltered": "",
"search": " ",
"paginate": {
"first": "Erste",
"last": "Letzte",
"next": "Vor",
"previous": "Zurück"
},
}
});
you can use:
"order": [ [ 1, "asc" ], [ 3, "desc" ] ],
I have done following code and now iI want to add edit column in Bootstrap Datatable with server side functionality in MVC and Bootstrap. Finally I want proper CRUD operation, so how can I approach for this?
<script type="text/javascript">
var assetListVM;
$(function () {
assetListVM = {
dt: null,
init: function () {
dt = $('#assets-data-table').DataTable({
"serverSide": true,
"processing": true,
"ajax": {
"url": "#Url.Action("Get","Asset")"
},
"columns": [
{ "title": "ID", "data": "ID", "searchable": true },
{ "title": "Name", "data": "Name", "searchable": true },
{ "title": "City", "data": "City", "searchable": true },
{ "title": "EmpCode", "data": "EmpCode", "searchable": true },
{ "title": "DOJ", "data": "DOJ", "searchable": true },
{ "title": "Address", "data": "Address" },
{ "title": "DOB", "data": "DOB" }
],
"lengthMenu": [[10, 25, 50, 100], [10, 25, 50, 100]],
});
}
}
// initialize the datatables
assetListVM.init();
});
</script>
I'm trying to set the width of a cell in a jQuery datatable upon initialization and it never seems to work. I've have tried what the official site recommends and other examples. Below are some of the options I have tried. Please help on what I'm doing wrong?
Ex: 1
$('#dataTables-comments').DataTable({
"bLengthChange": false,
"bFilter": false,
"iDisplayLength": 5,
"aoColumns": [{
"sWidth": "50%"
},
{
"sWidth": null
},
{
"sWidth": null
},
{
"sWidth": null
},
{
"sWidth": null
}
],
"responsive": true
});
Ex: 2
$('#dataTables-tbl').DataTable({
"bLengthChange": false,
"bFilter": false,
"iDisplayLength": 5,
"columnDefs": [{
"width": "50%",
"targets": 0
}],
"responsive": true
});
Ex: 3
$('#dataTables-tbl').DataTable({
"bLengthChange": false,
"bFilter": false,
"iDisplayLength": 5,
"columns": [{
"width": "50%"
}, {
"width": "10%"
}, {
"width": "10%"
}, {
"width": "10%"
}, {
"width": "10%"
}],
"responsive": true
});
As with any other usage of a CSS percentage value, the value must be a percentage of something. If the table itself not have a defined width, then 10% is untranslatable. So give your table a width :
#dataTables-comments {
width: 800px;
}
and be sure to turn off autoWidth so dataTables not begin to overrule the predefined column widths :
$('#dataTables-tbl').DataTable({
autoWidth: false, //<---
"bLengthChange": false,
"bFilter": false,
"iDisplayLength": 5,
"columns": [{
"width": "50%"
}, {
"width": "10%"
}, {
"width": "10%"
}, {
"width": "10%"
}, {
"width": "10%"
}],
"responsive": true
});