Am new to JavaScript & jQuery. Using jQuery datatables to populate data from JSON API. Table Header is also dynamic which means JSON variable as header text. How to add the total(Column & Row). Want rowwise total and columnwise total.
In this table want to add the Total text at the end of the row and column. Row total and column total.
Ajax Coding:-
function manufacturingSummary(todayDate) {
$('.loader').show();
$.ajax({
url : adminBaseUrl + "mfgSummary",
type : "POST",
crossDomain : true,
data : {
"summary_date" : todayDate
},
success : function(data) {
if (data.status == 1) {
$('.loader').hide();
var summaryColumns = [];
$.each( data.prodMfgSummary[0], function( key, value ) {
var items = {};
items.data = key;
items.title = key;
items.orderable = false;
/*items.className = "dt-body-right { text-align: center; }";*/
summaryColumns.push(items);
});
createProdSummaryTable(summaryColumns, data.prodMfgSummary);
} else {
$('.loader').hide();
$('#productionSummary').DataTable().clear().draw();
}
},
error : function(xhr, status) {
$('.loader').hide();
alert(status);
}
});
}
Table Creation Code:-
function createProdSummaryTable(columns, mfgSummaryProductData){
$('#productionSummary').dataTable({
"autoWidth" : false,
responsive : true,
"aaData" : mfgSummaryProductData,
"destroy" : true,
"aaSorting": [],
"bFilter": false,
"aoColumns" : columns,
"iDeferLoading" : 57
});
}
Help me to solve this issue.
Here is an example using columnDefs and its render and target options gor columnwise and footerCallback for rowwise
var dataSet = [{"name":"Wade Rodriguez","field1":21,"field2":22,"field3":20,"field4":21},{"name":"Maxwell Rush","field1":31,"field2":27,"field3":29,"field4":37},{"name":"Ruiz Murray","field1":40,"field2":30,"field3":27,"field4":31},{"name":"Tanner Crosby","field1":37,"field2":35,"field3":21,"field4":39},{"name":"Shelby Douglas","field1":25,"field2":25,"field3":30,"field4":30},{"name":"Haney Fulton","field1":35,"field2":26,"field3":38,"field4":27}]
$(document).ready(function() {
var my_columns = [];
$.each(dataSet[0], function(key, value) {
var my_item = {};
my_item.data = key;
my_item.title = key;
my_columns.push(my_item);
});
my_columns.push({
title: 'Total'
})
$(document).ready(function() {
$("#example").DataTable({
data: dataSet,
"columns": my_columns,
"columnDefs": [{
"render": function(data, type, row) {
return Object.values(row).reduce((a, b) => isNaN(b) ? a : a + b, 0)
},
"targets": my_columns.length - 1
}],
"footerCallback": function(row, data, start, end, display) {
$('#example tfoot').html('');
$('#example').append('<tfoot><td>Total</td></tfoot>');
var api = this.api();
var total = 0;
api.columns([1, 2, 3, 4], {
page: 'current'
}).every(function() {
var sum = this
.data()
.reduce(function(a, b) {
var x = parseFloat(a) || 0;
var y = parseFloat(b) || 0;
return x + y;
}, 0);
total += sum;
$('#example tfoot tr').append('<td>' + sum + '</td>');
});
$('#example tfoot tr').append('<td>' + total + '</td>');
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="//cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" rel="stylesheet" />
<script src="//cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<table id="example" class="display" cellspacing="0" width="100%">
</table>
Related
when i click one item in a.jsp, which is made by b.js calls c.js's function of getGrid() to show one more table.
it shows data of what i click in console well. but table grid-table-1 doesn't changed.
what i want is when i click another item, i want to call getGrid again to show data.
but in my code, only first click works
what is the problem? thanks!
itemClick: function(data){
getGrid(data.data.ITM_ID);
console.log(data.data.ITM_ID);
}
a.jsp
<nav>
<ul>
<li><a class="tri" href="javascript:void(0);" onclick="callMonth(50035);callSubtitle('살인'); this.onclick=null">살인</a></li>
<li><img src="css/f4f0edb08c97567ce6b0475a63bf7000.png" alt="Italian Trulli" width="40px" height="25px"></img></li>
<li>살인</li>
</ul>
</nav>
<div class="wrap">
<h3>등락율 순위</h3>
<table id="grid-table-1">
</table>
</div>
b.js
function callMonth(num) {
$.ajax({
url : 'http://www.crimestats.or.kr/openapi/Sttsapitbldata.do?KEY=373f2cc31cd449c992cc18004780f4e4&STATBL_ID=T184223019918177&DTACYCLE_CD=YY&WRTTIME_IDTFR_ID=2016&Type=json&CLS_ID='+num,
type : 'GET',
dataType: 'json',
success : function (resp) {
$(".chart01").html("");
console.log(resp);
var options = {
data : {
data: []
},
format: {
xAxis: function (_str) {
return _str.substr(0, 4);
},
yAxis: 'priceDataFormat'
},
func : {
tip: function (tipElement, data, rect) {
//console.log(data)
var date = data.xaxis.substr(0, 4);
var tip = '<div class="text">' + date + ' / ' + String(data.yaxis).format().trim() + '</div>';
tipElement.html(tip).show();
var arrow = '<div class="arrow" style="width: ' + tipElement.width() + 'px;"></div>';
tipElement.html(tipElement.html() + arrow).css({
left: rect.x - (tipElement.width() / 2), top: rect.y - 35
});
},
itemClick: function(data){
getGrid(data.data.ITM_ID);
console.log(data.data.ITM_ID);
}
},
use : {
animate : true,
aCrossLine: true
}
};
var rows = resp.Sttsapitbldata[1].row;
if (rows) {
var representativeRow;
for (i = 1; i < 13; i++) {
representativeRow = rows[i];
itemNm2 = representativeRow.ITM_NM;
dataV = representativeRow.DTA_VAL;
itm_id= representativeRow.ITM_ID;
/* console.log(itemNm2);
console.log(dataV);
console.log(itm_id);*/
options.data.data.push({DTA_VAL: dataV, ITM_NM: itemNm2, ITM_ID:itm_id});
}
var series = {
"main": {
"s1": {series: 'column', xaxis: 'ITM_NM', yaxis: 'DTA_VAL'}
}
};
event.stopPropagation();
var chart = webponent.chart.init($('.chart01'), options, styles, series);
}
}, /*error: function (xhr, status, error) {
alert("err")
}*/
});
}
c.js
function getGrid(itm_id_num) {
$(".grid-table-1").html("");
var table1 = $('#grid-table-1');
var template1 = $('#grid-template-1');
var grid1 = webponent.grid.init(table1, template1);
var body = [];
$.ajax({
dataType: 'json',
url : 'http://www.crimestats.or.kr/openapi/Sttsapitbldata.do?KEY=373f2cc31cd449c992cc18004780f4e4&STATBL_ID=T184223019918177&DTACYCLE_CD=YY&WRTTIME_IDTFR_ID=2016&Type=json&ITM_ID='+itm_id_num,
success : function (resp) {
var options = {
data: {
data: []
}
};
var rows = resp.Sttsapitbldata[1].row;
//console.log(rows);
if (rows) {
var representativeRow;
for (i = 11; i < 100; i++) {
representativeRow = rows[i];
itemNm2 = representativeRow.ITM_NM;
dataV = representativeRow.DTA_VAL;
stable_id = representativeRow.STATBL_ID;
cls_nm = representativeRow.CLS_NM;
cls_id = representativeRow.CLS_ID;
/* console.log(itemNm2);
console.log(dataV);*/
options.data.data.push({
ITM_NM : itemNm2,
STATBL_ID: stable_id,
CLS_NM : cls_nm,
CLS_ID : cls_id,
DTA_VAL : dataV
});
}
grid1.appendRow(options.data.data);
}
}
});
}
I have a dataTable that each row in it has a checkbox and up or down buttons to move rows. But if I check a checkbox and then move the row, checkbox change to unchecked state.
How can I prevent this event and hold the checkbox checked?
{ name: 'name',
data: 'name',
title: 'Name',
searchable: true,
sortable: false,
render: function (data, type, full, meta) {
if (type === 'display') {
var $span = $('<span></span>');
$('<input type="checkbox">').appendTo($span);
return $span.html();
}
return data;
}
},
here is my code : jsFiddle
You can save the states in variable and after drawing table can check and update the state of checkboxes
Fiddle https://jsfiddle.net/jdvusytn/1/
function moveRow(row, direction) {
var index = table.row(row).index();
var order = -1;
if (direction === 'down') {
order = 1;
}
var data1 = table.row(index).data();
data1.order += order;
var data1Checked = $(table.row(index).node()).find('input[type=checkbox]').prop('checked');
var data2 = table.row(index + order).data();
data2.order += -order;
var data2Checked = $(table.row(index + order).node()).find('input[type=checkbox]').prop('checked');
table.row(index).data(data2);
table.row(index + order).data(data1);
table.page(0).draw(false);
$(table.row(index + order).node()).find('input[type=checkbox]').prop('checked', data1Checked);
$(table.row(index).node()).find('input[type=checkbox]').prop('checked', data2Checked)
}
I'm using DataTables to create table. One of columns contains 'i' element and hidden input. I would like to filter data rows by that hidden value, but I can't manage to do that. As far I found that problem is in search() method, I suppose it doesn't search in children elements like 'input' in which I'm keeping my value.
Code fragment:
var select = $('<select><option value=""></option><option value="true">Accepted</option><option value="false">Rejected</option></select>')
.appendTo($(column.footer()).empty())
.on('change', function () {
var val = $(this).val();
column.search(val, true, false) // problem is here
.draw(true);
});
Nevermind, I've managed to achieve this on my own. I needed to define "columnDefs" and inside this "targets" which are columns that you want to filter and "render".
Here's the code:
var table = $('#dataCheck').DataTable({
"sDom": "ltp",
"columnDefs": [{
"targets": [6],
"render": function ( data, type, full, meta ) {
if(type === 'filter'){
return $('#dataCheck').DataTable().cell(meta.row, meta.col).nodes().to$().find('input').val();
} else {
return data;
}
}
}],
initComplete: function () {
this.api().columns().every(function (i) {
var column = this;
if (i == 6)
{
var select = $('<select><option value="..."></option><option value="true">Accepted</option><option value="false">Rejected</option></select>')
.appendTo($(column.footer()).empty())
.on('change', function () {
var val = $(this).val();
column.search(val, true, false)
.draw(true);
});
column.data().unique().sort().each(function (d, j) {
select.append('<option value="' + d + '">' + d + '</option>')
});
}
});
}
});
I am trying to make two functions work together that both work on their own.
Number 1: Is my table with a dropdown filter inside a control panel which I am trying to add a secondary checkbox filter to, everything works fine here.
http://jsfiddle.net/btofjkus/12/
$(document).ready(function () {
$('#example').DataTable({
ordering: false,
bLengthChange: false,
initComplete: function () {
this.api().columns(2).every(function () {
var column = this;
var select = $('<select><option value="">Show all</option></select>')
.appendTo($("#control-panel").find("div").eq(1))
.on('change', function () {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val());
column.search(val ? '^' + val + '$' : '', true, false)
.draw();
});
console.log(select);
column.data().unique().sort().each(function (d, j) {
select.append('<option value="' + d + '">' + d + '</option>')
});
});
}
});
console.log()
});
Number 2: Is an example I found online of filtering a DataTable with a button as you can see it works on its own but I am trying to change it slightly from a button to a checkbox so the filter can be released once it is unchecked.
You will have noticed the checkbox I made for this in Number 1. #checkbox-filter.
https://jsfiddle.net/annoyingmouse/ay16vnp1/
$(function () {
var dataTable = $('#example').DataTable({
searching: true,
info: false,
lengthChange: false
});
$('#filterButton').on('click', function () {
dataTable.draw();
});
});
$.fn.dataTable.ext.search.push(
function( settings, data, dataIndex ) {
var target = 'Software Engineer';
var position = data[1]; // use data for the age column
if (target === position){
return true;
}
return false;
}
);
Now you can see the two functions I am trying to put all this together into one table (Number 1) at http://jsfiddle.net/btofjkus/12/.
What I want to do is create a checkbox filter for "Software Engineers" from the "Position" column in Number 1.
This looks complicated when I write it down with all these codeblocks but it's really just merging two functions together in the correct way.
I have tried tearing the code apart myself and gluing it together but everything I try seems to be wrong.
Example: (failure)
$(document).ready(function () {
$('#example').DataTable({
ordering: false,
bLengthChange: false,
initComplete: function () {
this.api().columns(2).every(function () {
var column = this;
var select = $('<select><option value="">Show all</option></select>')
.appendTo($("#control-panel").find("div").eq(1))
.on('change', function () {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val());
column.search(val ? '^' + val + '$' : '', true, false)
.draw();
});
console.log(select);
column.data().unique().sort().each(function (d, j) {
select.append('<option value="' + d + '">' + d + '</option>')
});
});
}
});
console.log()
});
$(document).ready(function() {
if $('#checkbox-filter').is(':checked' function() {
$.fn.dataTable.ext.search.push(
function( settings, data, dataIndex ) {
var target = 'Software Engineer';
var position = data[1]; // use data for the age column
if (target === position){
return true;
}
return false;
}
);
});
});
As you can see above I tried mashing the code together with no luck, I have also tried some methods that seem to invoke the function but not when #checkbox-filter is checked.
The example below makes the dropdown filter only select "Software Engineers" from the "Position" column which is my criteria for this checkbox filter (but only when its checked).
$(document).ready(function () {
$('#example').DataTable({
ordering: false,
bLengthChange: false,
initComplete: function () {
this.api().columns(2).every(function () {
var column = this;
var select = $('<select><option value="">Show all</option></select>')
.appendTo($("#control-panel").find("div").eq(1))
.on('change', function () {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val());
column.search(val ? '^' + val + '$' : '', true, false)
.draw();
});
console.log(select);
column.data().unique().sort().each(function (d, j) {
select.append('<option value="' + d + '">' + d + '</option>')
});
});
}
});
console.log()
});
$.fn.dataTable.ext.search.push(
function( settings, data, dataIndex ) {
var target = 'Software Engineer';
var position = data[1]; // use data for the position column
if (target === position){
return true;
}
return false;
}
);
How can I make this work only when the checkbox is selected. And release when it is deselected.
UPDATE:
This kind of works but not as it should (once checked try interacting with the dropdown filter) you will see it kind of works, but it doesn't change back when it is unchecked, it also does not filter the visible data when checked meaning I have to interact with the dropdown menu to see results. How can I fix this?
http://jsfiddle.net/btofjkus/13/
$(document).ready(function () {
$('#example').DataTable({
ordering: false,
bLengthChange: false,
initComplete: function () {
this.api().columns(2).every(function () {
var column = this;
var select = $('<select><option value="">Show all</option></select>')
.appendTo($("#control-panel").find("div").eq(1))
.on('change', function () {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val());
column.search(val ? '^' + val + '$' : '', true, false)
.draw();
});
console.log(select);
column.data().unique().sort().each(function (d, j) {
select.append('<option value="' + d + '">' + d + '</option>')
});
});
}
});
console.log()
});
//changes below
$('#checkbox-filter').change(function() {
if ($(this).is(':checked')) {
$.fn.dataTable.ext.search.push(
function( settings, data, dataIndex ) {
var target = 'Software Engineer';
var position = data[1]; // use data for the position column
if (target === position){
return true;
}
return false;
}
);
}
});
Here is the working solution jsfiddle
$(document).ready(function () {
var dataTable = $('#example').DataTable({
ordering: false,
bLengthChange: false,
initComplete: function () {
this.api().columns(2).every(function () {
var column = this;
var select = $('<select><option value="">Show all</option></select>')
.appendTo($("#control-panel").find("div").eq(1))
.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>')
});
});
}
});
$('#checkbox-filter').on('change', function() {
dataTable.draw();
});
$.fn.dataTable.ext.search.push(
function( settings, data, dataIndex ) {
var target = 'Software Engineer';
var position = data[1]; // use data for the age column
if($('#checkbox-filter').is(":checked")) {
if (target === position) {
return true;
}
return false;
}
return true;
}
);
});
I am using jqGrid and I added a column of checkboxes to the grid but I want to alert which checkbox is checked .. here is my code
dataGrid.prototype = {
display: function () {
var self = this;
var html = [];
var check = 0;
html.push("<table id='" + this.id + "" + "'class='table'>\n</table>");
html.push("<div id='pagger_" + this.id + "'></div>");
$('body').append(html.join(""));
$("#" + this.id).jqGrid({
url: "index.jsp",
styleUI: 'Bootstrap',
datatype: "local",
data: this.data,
colModel: this.getColModels(this.data[0]),
onSelectRow: this.editRow,
viewrecords: true,
width: 1300,
height: 250,
rowNum: 50,
pager: "#pagger_" + this.id,
loadComplete: function () {
var iCol = self.getColumnIndexByName('Enable');
var rows = $("#" + this.id).jqGrid('getGridParam', 'data');
var i;
var c = rows.length;
for (i = 0; i < c; i += 1) {
$(rows[i].cells[iCol]).click(
function (e) {
var id = $(e.target).closest('tr')[0].id, isChecked = $(e.target).is(':checked');
alert("checked:" + isChecked);
// you can also get the
// values of the row
// data
alert('clicked on the checkbox in the row with id=' + id + '\nNow the checkbox is ' + (isChecked ? 'checked' : 'not checked'));
});
}
}
});
},
getColNames: function (data) {
var keys = [];
for (var key in data) {
if (data.hasOwnProperty(key)) {
keys.push(key);
}
}
return keys;
},
getColModels: function (data) {
var colNames = this.getColNames(data);
var colModelsArray = [];
var str2;
for (var i = 0; i < colNames.length; i++) {
var str1;
str1 = {
name: colNames[i],
index: colNames[i],
align: 'center',
editable: true,
edittype: "text",
};
colModelsArray.push(str1);
}
str2 = {
name: 'Enable',
index: 'Enable',
formatter: 'checkbox',
editable: true,
edittype: 'checkbox',
width: 60,
align: 'center',
formatoptions: {
disabled: false
},
editoptions: {
value: '1:0'
},
};
colModelsArray.push(str2);
return colModelsArray;
},
getColumnIndexByName: function (columnName) {
var cm = $("#" + this.id).jqGrid('getGridParam', 'colModel'), i, l;
for (i = 0, l = cm.length; i < l; i += 1) {
if (cm[i].name === columnName) {
return i;
}
}
return -1;
},
};
hint ..
the data is json object
whenever i print rows[i] it gives me [object object]
Whats wrong here?
You can trust delegation instead of adding a handler to every checkbox. Let's assume you put an ID to the container, like #containerDataGrid:
$("#containerDataGrid").on("click", "input[type=checkbox]", function(e){
var $this = $(this); //this is the checkbox
//this is more reliable than e.target,
// because it DOES point to the input not some child it could have
var $row = $this.closest("tr"); //in case the rows are tr. If not, change by the class or parameter identifying a row
var id = $row.attr("id"); //here's the ID you want! :D
console.log("The checkbox in the row: ",$row, " which has id= ", id, " is " $this.is(":checked")?"checked":"not checked");
});
If you only wanted to get some particular checkbox, you can make the "input[type=checkbox]"selector more specific, adding a class for instance:
"input[type=checkbox].the-checkbox-I-want"
or making sure it's the child of a wrapper:
".wrapper-of-my-beloved-checkbox > input[type=checkbox]"