How do I iterate thru a specific column in a DataTable? - javascript

I have a JSON file that looks like
[
{
"Title": "Something",
"FileName": "2014/mycollege/myvolume.pdf",
"Course": "01 - Dangerous Book for Boys",
"Year": "2014",
"Category": "Ethics",
"Group": "East Campus"
},
function getMyEdMaterials(result) {
$.getJSON("/materials/assets/json/materials.json", function(data) {
for (var key in data) {
datatableObject[data[key].Group] = datatableObject[data[key].Group] || [];
datatableObject[data[key].Group].push(data[key]);
datatableObject["all"] = datatableObject["all"] || [];
datatableObject["all"].push(data[key]);
}
for (var key in datatableObject) {
console.log(key.toLowerCase().replace(/\s/g, "-"));
console.log(datatableObject[key]);
var tableInstance = $('#' + key.toLowerCase().replace(/\s/g, "-") + '-table').DataTable({
bInfo: true,
bFilter: true,
columns: [{
title: "Title",
width: "30%",
render: function(data, type, row) {
return "" + row.Title + "";
}
},
{
title: "Course",
width: "30%",
data: "Course"
},
{
title: "Year",
width: "10%",
//data: "Year"
render: function(data, type, row) {
//year = year.push(row.Year);
return row.Year;
}
},
{
title: "Category",
width: "5%",
data: "Category"
},
{
title: "FileName",
width: "5%",
data: "FileName"
},
{
title: "Group",
width: "5%",
data: "Group"
}
],
columnDefs: [{
visible: false,
targets: [3, 4, 5]
}],
data: datatableObject[key],
deferRender: true,
dom: "<'toolbar'frltip >",
initComplete: function() {
this.api().columns(2).every(function() {
var column = this;
->>> having trouble getting the data from the column <<<---
if ((column == undefined) || (column == null)) {
console.log("data is null / undefined");
} else {
column.data().unique().sort().each(function(d, j) {
if ((d !== undefined) || (d !== null)) {
console.log(d + " is the year");
}
});
}
})
},
lengthMenu: [
[25, 50, 100, -1],
[25, 50, 100, "All"]
],
order: [
[2, 'desc'],
[3, 'asc'],
[1, 'asc'],
[0, 'asc']
],
orderMulti: true,
responsive: true,
});
}
})
};
What is the best way to get the data from the 3rd column from the DataTable?
Thanks

To get the data, just use
tableInstance.column(3).data()
or, if you want it in an array,
tableInstance.column(3).data().toArray()

Related

Convert json data to object

Good Day Developers!
I'm facing issue in JSON object received from MVC controller to AJAX success request.
The response which received is below.
[
{"name":"ERP Developer","value":2},
{"name":"Software Engineer","value":2},
{"name":"Dot Net Developer","value":2},
{"name":"Apex Developer","value":0},
{"name":"test","value":1}
]
But i want to make it like below.
{
"name": [
"ERP Developer",
"Software Engineer"
],
"Value": [
5,
10
]
}
Problem: Because i'm creating Bar chart using ECHARTS library but i want series name instead of number please see below image for reference.
function loadBarChart(data,title = "JobData",subtext = "Artistic Milliners") {
//var BarDBData = data;
var BarDBData = data;
//var BarDBData = JSON.parse('{"name":["ERP Developer","TEST"],"test":[5,10]}');
console.log(BarDBData);
var chartDom = document.getElementById('BarChart');
var myChart = echarts.init(chartDom);
var option;
option = {
title: {
text: title,
subtext: subtext
},
tooltip: {
trigger: 'axis'
},
toolbox: {
show: true,
feature: {
dataView: { show: true, readOnly: false },
magicType: { show: true, type: ['line', 'bar'] },
saveAsImage: { show: true }
}
},
calculable: true,
xAxis: [
{
type: 'category',
// prettier-ignore
//data: ["ERP Developer", "Software Engineer"],
data: BarDBData,
axisLabel: { interval: 0, rotate: 30 }
}
],
yAxis: [
{
type: 'value'
}
],
dataZoom: [
{
show: true,
start: 04,
end: 100
},
{
type: 'inside',
start: 44,
end: 100
},
{
show: true,
yAxisIndex: 0,
filterMode: 'empty',
width: 30,
height: '80%',
showDataShadow: false,
left: '93%'
}
],
series: [
{
name: "test",
type: 'bar',
data: BarDBData,
//data: [2.0, 4.9, 4, 9, 4],
itemStyle: {
color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
{ offset: 0, color: '#83bff6' },
{ offset: 0.5, color: '#188df0' },
{ offset: 1, color: '#188df0' }
])
},
markPoint: {
data: [
{ type: 'max', name: 'Max' },
{ type: 'min', name: 'Min' }
]
}
}
]
};
option && myChart.setOption(option);
}
you can just map through array and extract values into another array
const result = {}
const arr = [{"name":"ERP Developer","value":2},{"name":"Software Engineer","value":2},{"name":"Dot Net Developer","value":2},{"name":"Apex Developer","value":0},{"name":"test","value":1}]
arr.forEach(row => {
for (let i in row) {
if (result[i]) {
result[i].push(row[i])
} else {
result[i] = [row[i]]
}
}
})
console.log(result)
Just reduce() it into the desired shape:
const response = [
{"name":"ERP Developer","value":2},
{"name":"Software Engineer","value":2},
{"name":"Dot Net Developer","value":2},
{"name":"Apex Developer","value":0},
{"name":"test","value":1}
];
const mapped = response.reduce(
(acc,x) => {
acc.name.push( x.name );
acc.Value.push( x.value );
return acc;
},
{ name: [], Value: [] }
);

html datatable compact column width

I am trying to make a js datatable that has a column called 'Audio', which right now does not utilize space very well:
I'm trying to change it so that the Audio column is only as wide as its widest text element, basically so it has no blank space:
I've tried manually setting the max-width but it hasn't made any difference, and I've explored some datatables options but with no luck so far
https://jsfiddle.net/1mzqf23w/
$(document).ready(function() {
var data = JSON.parse('[{"itemId":1,"audio":"01 Hey DJ.flac","format":"flac","length":"00:03:27","audioFilepath":"C:\Users\marti\Documents\ous supreme team - (1986) rappin\Hey DJ.flac","trackNum":1,"album":"Rappin","year":1986,"artist":"Worlds Famous Supreme Team"}, {"itemId":2,"audio":"02 Wow Dude DJ.flac","format":"flac","length":"00:03:27","audioFilepath":"C:\Users\marti\Documents\ous supreme team - (1986) rappin\Hey DJ.flac","trackNum":1,"album":"Rappin","year":1986,"artist":"Worlds Famous Supreme Team"}]')
//setup table
var reorder = false;
var searched = false;
var origIndexes = [];
var origSeq = [];
var origNim = [];
let tableId = `#1_table`;
//create table
var table = $(tableId).DataTable({
"autoWidth": true,
"pageLength": 5000,
select: {
style: 'multi',
selector: 'td:nth-child(2)'
},
columns: [
{ "data": "sequence" },
{ "data": "#" },
{ "data": "selectAll" },
{ "data": "audio" },
{ "data": "length" },
{ "data": "audioFilepath" },
{ "data": "trackNum" },
{ "data": "album" },
{ "data": "year" },
{ "data": "artist" },
//{ "data": "imgSelection" },
],
columnDefs: [
{ //invisible sequence num
searchable: false,
orderable: false,
visible: false,
targets: 0,
},
{ //visible sequence num
searchable: false,
orderable: false,
targets: 1,
},
{//select all checkbox
"className": 'selectall-checkbox',
"className": "text-center",
searchable: false,
orderable: false,
targets: 2,
},
{//audio filename
targets: 3,
type: "natural"
},
/*
{//audio format
targets: 4,
type: "string"
},
*/
{ //audio file length
targets: 4,
type: "string"
},
/*
{ //video output format
targets: 6,
type: "string",
orderable: false
},
*/
{//audioFilepath
targets: 5,
visible: false,
},
{//trackNum
targets: 6,
visible: true,
orderable: true,
},
{//album
targets: 7,
visible: true,
orderable: true,
},
{//year
targets: 8,
visible: true,
orderable: true,
},
{//artist
targets: 9,
visible: true,
orderable: true,
},
/*
{ //image selection
targets: 7,
type: "string",
orderable: false,
className: 'text-left'
},
*/
],
"language": {
"emptyTable": "No files in this upload"
},
dom: 'rt',
rowReorder: {
dataSrc: 'sequence',
},
});
//add dataset to table
var count = 1;
data.forEach(function (i) {
table.row.add({
"sequence": i.itemId,
"#": `<div style='cursor: pointer;'><i class="fa fa-bars"></i> ${count}</div>`,
"selectAll": '<input type="checkbox">',
"audio": i.audio,
"length": i.length,
//"outputFormat": i.vidFormatSelection,
//"outputLocation": "temp output location",
"audioFilepath": i.audioFilepath,
"trackNum": i.trackNum,
"album": i.album,
"year": i.year,
"artist": i.artist,
//"imgSelection": i.imgSelection,
}).node().id = 'rowBrowseId' + i.sampleItemId;
count++;
});
//draw table
table.draw();
} );
If you are able to use css then try:
{//audio filename
targets: 3,
type: "natural",
className: 'track-name'
},
.track-name {
width: 0 !important;
white-space: nowrap;
}

How to add Dropdown in JQUERY DataTable?

I want to add Drop down with in a Data Table. But it's not working.
Here I am adding the code I tried:
_dataTables.markAttendanceTable = $('#markAttendanceTable').DataTable(
{
dom: '<"pull-right"f>rt<"bottom"ip><"clear">',
ordering: false,
searching: false,
paging: true,
pageLength: 10,
fixedColumns: false,
data: GetAllMarkAttendance(eventId),
language: {
search: "_INPUT_",
searchPlaceholder: "Search"
},
columns: [
{ "data": "Login.Name", "defaultContent": "<i>-</i>" },
{"data":null ,
render: function (d, t, r) {
debugger;
var $select = $("<select></select>", {
//"id": //r[0]+"start",
"id": "Select",
"value": "Select"
});
$.each(attended, function(k,v){
var $option = $("<option></option>", {
"text": v,
"value": k
});
if(d === v){
$option.attr("selected", "selected")
}
$select.append($option);
});
return $select.prop("outerHTML");
}
},
],
columnDefs: [
{ className: "text-left", "targets": [0] },
{ className: "text-center", "targets": [] },
//{ width: "30%", "targets": [0] },
//{ width: "25%", "targets": [1] },
],
});
Please give me your suggestions.

Free jqGrid 4.14 Grouping header not formatting date custom totals not working

Using free jqGrid 4.14 attempting to set up a time logging grid searched SO, github and trirand and of course google but haven't found anything that worked for me. I have most of the basic functionality working but there are a few things that I have been working on for a week now and need help on completing. An image will be attached showing what I have so far and will include my code/json. What I have not been able to accomplish is the group headers would like to put in the group date in the first column and the date for the associated days in their respective columns. The second grouping is showing the date correctly but the first shows /date with a long number. the fields are identical in properties and the way the json is brought in. Need totals both column and a summary row for each group. Because the time is entered as a string of HH:MM the custom totals are calculated converting from string to seconds summed and back to string. If the totals are over 40 hours then the color should be red. Hoping that can be done.
JSON:
[
"total": 5,
"page": 1,
"records": 5,
"rows":
{
"CDPayCodeId": 1,
"EndPayPeriod": "2017-05-15T00:00:00.0000000-05:00",
"Fri": null,
"Mon": null,
"PersonId": 1,
"Sat": null,
"Sun": null,
"Thu": null,
"Total": null,
"Tue": null,
"Wed": "00:15",
"WeekStart": "2017-04-30T00:00:00.0000000-05:00"
},
{
"CDPayCodeId": 2,
"EndPayPeriod": "2017-05-15T00:00:00.0000000-05:00",
"Fri": null,
"Mon": null,
"PersonId": 1,
"Sat": null,
"Sun": null,
"Thu": null,
"Total": null,
"Tue": null,
"Wed": "06:15",
"WeekStart": "2017-04-30T00:00:00.0000000-05:00"
},
{
"CDPayCodeId": 1,
"EndPayPeriod": "2017-05-15T00:00:00.0000000-05:00",
"Fri": null,
"Mon": "04:30",
"PersonId": 1,
"Sat": null,
"Sun": null,
"Thu": null,
"Total": null,
"Tue": null,
"Wed": null,
"WeekStart": "2017-05-14T00:00:00.0000000-05:00"
},
{
"CDPayCodeId": 2,
"EndPayPeriod": "2017-05-15T00:00:00.0000000-05:00",
"Fri": null,
"Mon": null,
"PersonId": 1,
"Sat": null,
"Sun": "04:30",
"Thu": null,
"Total": null,
"Tue": null,
"Wed": null,
"WeekStart": "2017-05-14T00:00:00.0000000-05:00"
},
{
"CDPayCodeId": 3,
"EndPayPeriod": "2017-05-15T00:00:00.0000000-05:00",
"Fri": null,
"Mon": "04:30",
"PersonId": 1,
"Sat": null,
"Sun": null,
"Thu": null,
"Total": null,
"Tue": null,
"Wed": null,
"WeekStart": "2017-05-14T00:00:00.0000000-05:00"
}
]
HTML
<table id="TimesheetGrid"></table>
<script>
var PCList = '#ViewBag.PCList'
var selectedId = '#ViewBag.PId'
</script>
JS Code
$(function () {
"use strict";
var $grid = $("#TimesheetGrid"), recreateFilterToolbar = function () { $(this).jqGrid("destroyFilterToolbar").jqGrid("filterToolbar"); };
var editSettings = {
//recreateForm:true,
jqModal: false,
reloadAfterSubmit: false,
closeOnEscape: true,
savekey: [true, 13],
closeAfterEdit: true
};
var addSettings = {
//recreateForm:true,
jqModal: false,
reloadAfterSubmit: false,
savekey: [true, 13],
closeOnEscape: true,
closeAfterAdd: true
};
var delSettings = {
jqModal: false,
reloadAfterSubmit: false,
savekey: [true, 13],
closeOnEscape: true,
closeAfterAdd: true
};
var inLineNaveSettings = {
add: true,
addtext: 'Inline',
addtitle: 'Add new record inline',
edit: false
};
function SecondsFromTime(time) {
var timeParts = time.match(/(\d{2}):(\d{2})/);
if (timeParts !== null) {
var timeUntil = moment.duration({
hours: timeParts[1],
minutes: timeParts[2],
});
var timeSeconds = timeUntil.as('seconds');
return timeSeconds;
}
}
function calcTotal(cellvalue, options, rowObject) {
//var time = '12d 00:57:30';
var secs = 0;
var timeParts = '';
for (var x = 1; x < 8; x++) {
if (x === 1 && rowObject.Sun !== null) { secs = SecondsFromTime(rowObject.Sun); }
else if (x === 2 && rowObject.Mon !== null) { secs += SecondsFromTime(rowObject.Mon); }
else if (x === 3 && rowObject.Tue !== null) { secs += SecondsFromTime(rowObject.Tue); }
else if (x === 4 && rowObject.Wed !== null) { secs += SecondsFromTime(rowObject.Wed); }
else if (x === 5 && rowObject.Thu !== null) { secs += SecondsFromTime(rowObject.Thu); }
else if (x === 6 && rowObject.Fri !== null) { secs += SecondsFromTime(rowObject.Fri); }
else if (x === 7 && rowObject.Sat !== null) { secs += SecondsFromTime(rowObject.Sat); }
}
return moment().startOf('day').seconds(secs).format('H:mm');
}
$grid.jqGrid({
autoencode: true,
url: '/Timesheet/GetTaskList?PId=' + selectedId,
editurl: '/Timesheet/UpdateTimesheet',
mtype: "GET",
caption: "Maintain Timesheet",
datatype: 'json',
loadonce: true,
//colNames: ['', 'PayCodeId', 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Total'],
colModel: [
{ name: 'PersonId', editable: 'hidden', hidden: true },
{ name: 'EndPayPeriod', editable: 'hidden', sorttype: "date", formatter: "date", formatoptions: { newformat: "n/j/Y" } },
{ name: 'WeekStart', editable: 'hidden', sorttype: "date", formatter: "date", formatoptions: { newformat: "n/j/Y" } },
{
name: 'CDPayCodeId', index: 'CDPayCodeId', label: 'Pay Code', align: "center", width: 90,
formatter: "select", autoResizable: true, sortable: false,
edittype: "select", editoptions: { value: PCList }
},
{ name: 'Sun', index: 'Sun', label: 'Sun', sortable: false, width: 50, autoResizable: true, summaryType: SumDay },
{ name: 'Mon', index: 'Mon', label: 'Mon', sortable: false, width: 50, autoResizable: true, summaryType: SumDay },
{ name: 'Tue', index: 'Tue', label: 'Tue', sortable: false, width: 50, autoResizable: true, summaryType: SumDay },
{ name: 'Wed', index: 'Wed', label: 'Wed', sortable: false, width: 50, autoResizable: true, summaryType: SumDay },
{ name: 'Thu', index: 'Thu', label: 'Thu', sortable: false, width: 50, autoResizable: true, summaryType: SumDay },
{ name: 'Fri', index: 'Fri', label: 'Fri', sortable: false, width: 50, autoResizable: true, summaryType: SumDay },
{ name: 'Sat', index: 'Sat', label: 'Sat', sortable: false, width: 50, autoResizable: true, summaryType: SumDay },
{
name: 'Total', index: 'Total', label: 'Total', sortable: false, sidth: 70, autoResizable: true,
formatter: calcTotal
},
{ name: "act", template: "actions", width: 60 }
],
//jsonReader: { id: "PersonId" },
height: '100%',
shrinkToFit: true,
autowidth: false,
rownumbers: false,
autoresizeOnLoad: false,
cmTemplate: { editable: true, autoResizable: true, align: 'right' },
iconSet: "fontAwesome",
rowNum: 10,
autoResizing: { compact: true },
rowList: [5, 10, 20, "10000:All"],
viewrecords: true,
pager: true,
//toppager: true,
sortname: "SortOrder",
sortorder: "asc",
inlineEditing: { keys: true, defaultFocusField: "PayCode", focusField: "PayCode" },
afterAddRow: function () {
recreateFilterToolbar.call(this);
$(this).trigger("reloadGrid", [{ current: true, fromServer: true }]);
},
afterSetRow: function () {
recreateFilterToolbar.call(this);
$(this).trigger("reloadGrid", [{ current: true, fromServer: true }]);
},
afterDelRow: function () {
recreateFilterToolbar.call(this);
$(this).trigger("reloadGrid", [{ current: true, fromServer: true }]);
},
grouping: true,
groupingView: {
groupField: ['EndPayPeriod', 'WeekStart'],
groupOrder: ['asc', 'asc'],
groupText: ['Pay Period {0}' , 'Week Start {0}'],
//groupOrder [] // can use html if needed
groupColumnShow: [false, false],
groupDataSorted: true,
//showSummaryOnHide: false,
groupSummary: [true, true],
hideFirstGroupCol: true,
plusicon: 'fa-minus',
minusicon: 'fa-plus'
}
}).jqGrid("gridResize");
$grid.jqGrid("navGrid", {
edit: editSettings,
add: addSettings,
del: delSettings,
search: false,
reloadGridOptions: { fromServer: true },
beforeRefresh: function () {
alert('In beforeRefresh');
grid.jqGrid('setGridParam', { datatype: 'json' }).trigger('reloadGrid');
}
});
$grid.jqGrid('inlineNav', inLineNaveSettings);
$("#SelectPerson").change(function () {
var selectedId = $("#SelectPerson").val();
$("#TimesheetGrid").jqGrid('setGridParam', { datatype: 'json', url: '/Timesheet/GetTaskList?PId=' + selectedId }).trigger('reloadGrid');
});
function SumDay(val, name, record) {
if (record[name] !== "" && record[name] !== null) {
var totalTime = SecondsFromTime(record[name]);
var totalTimeString = moment().startOf('day').seconds(totalTime).format('H:mm');
}
return totalTimeString;
}
});
First of all, it would be helpful if you post the demo, which can be used to reproduce the code. You can use JSFiddle, for example, and Echo service of JSFiddle to simulate the requests to the server. I created the demo based on your code and the test data
The main problem of your code is ignoring the first parameter (val in your code) of the custom summary function SumDay. The value of the parameter is "" initially and it will be the sum of previous elements of the group. You have to sum the value to the current value and return new sum value from the function. The fixed code could be the following:
function SumDay(val, name, record) {
var totalTime, totalTimeString;
if (record[name] !== "" && record[name] !== null) {
totalTime = SecondsFromTime(record[name]);
if (val !== "") {
totalTime += SecondsFromTime(val);
}
totalTimeString = moment().startOf('day').seconds(totalTime).format('HH:mm');
val = totalTimeString;
}
return val;
}
I fixed additionally .format('H:mm') to .format('HH:mm'), because you test for exactly two digits in SecondsFromTime (see time.match(/(\d{2}):(\d{2})/)).
The resulting demo https://jsfiddle.net/OlegKi/ag1160e3/ displays the results like on the picture below:

Flot line chart with categories not working

I have a flot chart with the following code:
var options = {
lines: {
show: true
},
points: {
show: true
},
xaxis: {
tickSize: 1,
mode: "categories"
}
};
var data = [];
data.push(
{"label": "Agrobiodiversity for consumption",
"data": [["January", 3.0], ["February", 3.9], ["March", 2.0], ["April", 1.2], ["May", 1.3], ["June", 2.5],
["July", 2.0], ["August", 3.1], ["September", 2.9], ["October", 0.9],["November", 0.5],["December", 1.8]]});
$.plot($("#flot-dashboard-chart"), data, options);
But I I get:
I have tried addigng the categories in the axis options but nothing seem to work.
Any idea what else do I need to add or what do I need to correct?
U can use my high chart, and u can remove unnecessary stuffs.
Demo with jsFiddle
var chart = Highcharts.chart('container', {
chart: {
type: 'bar'
},
title: {
text: ''
},
subtitle: {
text: ''
},
xAxis: {
labels: {
formatter: function() {
var link_array = ["first", "second", "third", "fourth"];
i = 0;
if (this.value == 'Sugammadex and related compounds')
return '' + this.value + '';
if (this.value == 'Cyclodextrin enabled diclofenac injection (generic Dyloject)')
return '' + this.value + '';
if (this.value == 'Cyclodextrins in biological products')
return '' + this.value + '';
if (this.value == 'Cyclodextrins as a new class of antibiotics')
return '' + this.value + '';
},
useHTML: true
},
categories: ['Sugammadex and related compounds',
'Cyclodextrin enabled diclofenac injection (generic Dyloject)', 'Cyclodextrins in biological products',
'Cyclodextrins as a new class of antibiotics'
],
title: {
text: null
}
},
yAxis: {
labels: {
formatter: function() {
var x_text = ["", "Feasibility study", "Lead / formulation Optimization", "Product Development", "Final product"];
return x_text[this.value];
}
},
title: {
text: '',
align: 'high'
},
tickInterval: 1
},
tooltip: {
formatter: function() {
var x_text = ["", "Feasibility study", "Lead / formulation Optimization", "Product Development", "Final product"];
return x_text[this.y];
}
},
plotOptions: {
bar: {
dataLabels: {
enabled: false
}
}
},
credits: {
enabled: false
},
series: [{
showInLegend: false,
data: [1, 2, 3, 4]
}]
});
$(document).ready(function() {
$("a").on('click', function(event) {
if (this.hash !== "") {
event.preventDefault();
var hash = this.hash;
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 800, function() {
window.location.hash = hash;
});
}
});
});
Well the "categories" mode is a plugin that need to be loaded in the HTML

Categories