Kendo grid insert new row with custom class - javascript

This is how I insert new data to kendo grid, however i want my added row have a custom class, so I can style my new added row with different background color. How can I achieve this ? I searching all the doc can't find any related
var dataSource = $('#grid').data('kendoGrid').dataSource;
dataSource.insert(0, {
"name":"ABC",
"age": 99
});

In order to add a new class to each newly row you can use .addClass(). But, every time you move to the next/prev page or add other rows you need to add again the class....
In order to achieve that you can save in a global array a list of all newly added row uuid and on dataBound event reapply the class.
Fiddle here
var newUUID = [];
$("#grid").kendoGrid({
navigatable: true,
filterable: true,
pageable: {
pageSize: 5,
alwaysVisible: false,
pageSizes: [5, 10, 20, 100]
},
dataBound: function(e) {
$.each(newUUID, function(idx, ele) {
if ($(ele).length != 0) {
$(ele).addClass('newRow');
}
})
}
});
$('#btn').on('click', function(e) {
var dataSource = $('#grid').data('kendoGrid').dataSource;
var x = dataSource.insert(0, {
"name":"ABC",
"age": 99
});
newUUID.push("[data-uid='" + x.uid + "']");
$("[data-uid='" + x.uid + "']").addClass('newRow');
})

You can look-up the newly added row by its UID and add the class to the row.
I explored the solution on this blog: "Simple Row Coloring in a KendoUI Grid"
const sampleData = getSampleData();
$(document).ready(() => {
$("#example-grid-wrapper").kendoGrid({
dataSource: {
data: sampleData.data,
schema: {
model: {
fields: sampleData.fields
}
}
},
columns: sampleData.columns
});
setTimeout(insertNewRecordAfterOneSecond, 1000);
});
function insertNewRecordAfterOneSecond() {
// Insert data
let dataGrid = $('#example-grid-wrapper').data('kendoGrid');
dataGrid.dataSource.insert(0, { id: 1, name: "Sam", location: "B", color: "blue", status: 0 });
// Re-scan table and lookup newly added row.
dataGrid = $('#example-grid-wrapper').data('kendoGrid');
let dataView = dataGrid.dataSource.view();
for (let i = 0; i < dataView.length; i++) {
if (dataView[i].id === 1) {
dataGrid.table.find("tr[data-uid='" + dataView[i].uid + "']").addClass("highlighted-row");
}
}
}
function getSampleData() {
return {
data : [
{ id: 2, name: "Grant", location: "A", color: "green", status: 1 },
{ id: 3, name: "Vaughan", location: "B", color: "red", status: 0 },
{ id: 4, name: "David", location: "A", color: "orange", status: 1 }
],
fields : {
id: { type: "number" },
name: { type: "string" },
location: { type: "string" },
color: { type: "string" }
},
columns : [
{ field: "id", title: "ID", width: "10%" },
{ field: "name", title: "Name", width: "30%" },
{ field: "location", title: "Location", width: "30%" },
{ field: "color", title: "Color", width: "20%" },
{ field: "status", title: "Status", width: "10%" }
]
};
}
.highlighted-row {
background: #FF0; /* Higlight row yellow */
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="http://kendo.cdn.telerik.com/2019.2.619/js/kendo.all.min.js"></script>
<link rel="stylesheet" href="http://kendo.cdn.telerik.com/2019.2.619/styles/kendo.common.min.css" />
<link rel="stylesheet" href="http://kendo.cdn.telerik.com/2019.2.619/styles/kendo.blueopal.min.css" />
<div id="example-grid-wrapper">
<div id="example-grid"></div>
</div>
Alternative
As suggested by gaetanoM.
const sampleData = getSampleData();
var insertedUidList = [];
$(document).ready(() => {
$("#example-grid").kendoGrid({
dataSource: {
data: sampleData.data,
schema: {
model: {
fields: sampleData.fields
}
}
},
columns: sampleData.columns,
// Suggested by gaetanoM
dataBound: function(e) {
$.each(insertedUidList, function(idx, uid) {
// Re-apply class to existing rows.
$(`tr[data-uid="${uid}"]`).addClass('highlighted-row');
});
}
});
// Insert two rows, one second apart.
insertRowsWithDelay([
{ id: 0, name: "Joseph", location: "A", color: "yellow", status: 1 },
{ id: 1, name: "Sam", location: "B", color: "blue", status: 0 },
], 1000)
});
function insertRowsWithDelay(data, delayBetween) {
if (data == null || data.length === 0) return;
setTimeout(() => {
insertNewRecord(data.pop());
insertRowsWithDelay(data, delayBetween);
}, 1000);
}
function insertNewRecord(record) {
record = $('#example-grid').data('kendoGrid').dataSource.insert(0, record);
insertedUidList.push(record.uid);
$(`[data-uid="${record.uid}"]`).addClass('highlighted-row');
}
function getSampleData() {
return {
data : [
{ id: 2, name: "Grant", location: "A", color: "green", status: 1 },
{ id: 3, name: "Vaughan", location: "B", color: "red", status: 0 },
{ id: 4, name: "David", location: "A", color: "orange", status: 1 }
],
fields : {
id: { type: "number" },
name: { type: "string" },
location: { type: "string" },
color: { type: "string" }
},
columns : [
{ field: "id", title: "ID", width: "10%" },
{ field: "name", title: "Name", width: "30%" },
{ field: "location", title: "Location", width: "30%" },
{ field: "color", title: "Color", width: "20%" },
{ field: "status", title: "Status", width: "10%" }
]
};
}
.highlighted-row {
background: #FF0; /* Higlight row yellow */
}
.highlighted-row.k-alt {
background: #DD0; /* Higlight row yellow */
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="http://kendo.cdn.telerik.com/2019.2.619/js/kendo.all.min.js"></script>
<link rel="stylesheet" href="http://kendo.cdn.telerik.com/2019.2.619/styles/kendo.common.min.css" />
<link rel="stylesheet" href="http://kendo.cdn.telerik.com/2019.2.619/styles/kendo.blueopal.min.css" />
<div id="example-grid"></div>

You can try to create a databound function for the grid and then try this inside the function
function onDataBound(e) {
var dataSource = $("#GridName").data("kendoGrid").dataSource;
var data = dataSource.data();
$.each(data, function (index, rowItem) {
if (data.length > 0) {
var rows = e.sender.tbody.children();
var row = $(rows[index]);
if (data[index].name == "ABC" ) {
row.addClass("NameColor");
}
}
});
}
<style>
.NameColor {
background-color: black;
}
</style>
Like this you can try..

Related

Kendo Grid Automatically Fit Column Width except for Specific Column

I am looking for a way to let column(index = n) (by index number) or column(headingText = 'Address') (by column name) fill the gap on my kendo grid.
I know how to automatically fit column widths for a Kendo Grid:
<div id="example">
<div id="grid"></div>
<script>
$(document).ready(function() {
var grid = $("#grid").kendoGrid({
dataSource: {
type: "odata",
transport: {
read: "https://demos.telerik.com/kendo-ui/service/Northwind.svc/Orders"
},
schema: {
model: {
fields: {
OrderID: {
type: "number"
},
ShipCountry: {
type: "string"
},
ShipCity: {
type: "string"
},
ShipName: {
type: "string"
},
OrderDate: {
type: "date"
},
ShippedDate: {
type: "date"
}
}
}
},
pageSize: 15
},
height: 550,
sortable: true,
resizable: true,
pageable: true,
dataBound: function() {
for (var i = 0; i < this.columns.length; i++) {
this.autoFitColumn(i);
}
},
columns: [{
field: "OrderDate",
title: "Order Date",
format: "{0:MM/dd/yyyy}"
},
{
field: "ShipCountry",
title: "Ship Country"
},
{
field: "ShipCity",
title: "Ship City"
},
{
field: "ShipName",
title: "Ship Name"
},
{
field: "ShippedDate",
title: "Shipped Date",
format: "{0:MM/dd/yyyy}"
},
{
field: "OrderID",
title: "ID"
}, {
field: "OrderDate",
title: "Order Date",
format: "{0:MM/dd/yyyy}"
},
{
field: "ShipCountry",
title: "Ship Country"
},
{
field: "ShipCity",
title: "Ship City"
},
{
field: "ShipName",
title: "Ship Name"
},
{
field: "ShippedDate",
title: "Shipped Date",
format: "{0:MM/dd/yyyy}"
},
{
field: "OrderID",
title: "ID"
}
]
});
});
</script>
</div>
<style>
#grid>table
{
table-layout: fixed;
}
</style>
I made a fiddle, but I don't know how to link in kendo grid:
https://jsfiddle.net/jp2code/p6cu5r29/2/
I could HARD CODE the column widths:
columns: [
{ field: "name", width: "200px" },
{ field: "tel", width: "10%" }, // this will set width in % , good for responsive site
{ field: "age" } // this will auto set the width of the content
],
But I'd like the grid to be more dynamic.
I can remove the empty space in a grid by leaving the autoFitColumn off of the last column:
<style>
.k-grid {
width: 700px;
}
</style>
<div id="grid1"></div>
<script>
function getMasterColumnsWidth(tbl) {
var result = 0;
tbl.children("colgroup").find("col").not(":last").each(function (idx, element) {
result += parseInt($(element).outerWidth() || 0, 10);
});
return result;
}
function adjustLastColumn() {
var grid = $("#grid1").data("kendoGrid");
var contentDiv = grid.wrapper.children(".k-grid-content");
var masterHeaderTable = grid.thead.parent();
var masterBodyTable = contentDiv.children("table");
var gridDivWidth = contentDiv.width() - kendo.support.scrollbar();
masterHeaderTable.width("");
masterBodyTable.width("");
var headerWidth = getMasterColumnsWidth(masterHeaderTable),
lastHeaderColElement = grid.thead.parent().find("col").last(),
lastDataColElement = grid.tbody.parent().children("colgroup").find("col").last(),
delta = parseInt(gridDivWidth, 10) - parseInt(headerWidth, 10);
if (delta > 0) {
delta = Math.abs(delta);
lastHeaderColElement.width(delta);
lastDataColElement.width(delta);
} else {
lastHeaderColElement.width(0);
lastDataColElement.width(0);
}
contentDiv.scrollLeft(contentDiv.scrollLeft() - 1);
contentDiv.scrollLeft(contentDiv.scrollLeft() + 1);
}
$("#grid1").kendoGrid({
dataSource: {
type: "odata",
transport: {
read: "https://demos.telerik.com/kendo-ui/service/Northwind.svc/Employees"
},
pageSize: 6,
serverPaging: true,
serverSorting: true
},
height: 430,
pageable: true,
resizable: true,
columnResize: adjustLastColumn,
dataBound: adjustLastColumn,
columns: [{
field: "FirstName",
title: "First Name",
width: "100px"
}, {
field: "LastName",
title: "Last Name",
width: "150px"
}, {
field: "Country",
width: "100px"
}, {
field: "City",
width: "100px"
}, {
field: "Title",
width: "200px"
}, {
template: " "
}]
});
</script>
But, I don't want to always leave the last column super wide to fill the page.
I am looking for a more generic example showing how to let column(index = n) or column(headingText = 'Address') be the column that fills the gap.
I did it! Sharing with others:
function refreshGridColumns(grid, skipField) {
var index = -1;
console.log('refreshGridColumns: grid.columns.length = ' + grid.columns.length);
var columns = grid.options.columns;
// find address column and do not autofit it so that the grid fills the page
for (var i = 0; i < grid.columns.length; i++) {
if (0 < columns.length) {
console.log('refreshGridColumns: field = ' + columns[i].field);
if (columns[i].field == skipField) { // columns[i].title -- You can also use title property here but for this you have to assign title for all columns
index = i;
} else {
grid.autoFitColumn(i);
}
} else {
grid.autoFitColumn(i);
}
console.log('refreshGridColumns: i = ' + i);
}
console.log('refreshGridColumns: index = ' + index);
}
Kudos to Jayesh Goyani for this answer:
https://stackoverflow.com/a/34349747/153923

Is there a way to make an entire row in Tabulator clickable to a cell in that row containing a unique URL for each row?

Using Tabulator, I have a cell which contains a unique URL that the entire row should link.
I've tried the following code:
{rowHandle:true, formatter:"handle", headerSort:false, frozen:true,
minwidth:30, minWidth:30},
{title:"Database", field:"database", minwidth:110, editor:"input"},
{title:"Environment", field:"environment", minwidth:140, editor:"input"},
{title:"Product", field:"product", minwidth:140, editor:"input"},
{title:"URL", field:"url", formatter:"link", minwidth:130,
editor:"input"},'''
$("#tabulator-example").tabulator({
rowClick:function(e,row){
},
});
The Tabulator table simply disappears each time I try to add the rowClick line of code from the example.
This is the way I've been creating tables (below).
Then in your rowClick function, you can access the row data:
rowClick: function (e, row) {
// alert("Row " + row.getData().id + " Clicked!!!!");
},
let dataTable = new Tabulator("#data-list", {
height: "84vh",
width: 150,
virtualDomBuffer: 30,
// layout: "fitDataFill",
layout: "fitColumns",
resizableColumns: false,
selectable: 1,
responsiveLayout: "hide",
placeholder: "No Data",
columns: [
{
title: "Meeting",
field: "startDate",
formatter: eventListRowFormatter,
variableHeight: true,
headerSort: false
},
{ formatter: deleteIcon, width: 5, align: "center", cellClick: deleteFromEventList }
],
rowClick: function (e, row) {
// do something
},
rowDeselected: function (row) {
// do something
},
ajaxLoader: false
});
Use Selectable selectable: true,
const tabledata = [{
id: 1,
name: "Oli Bob",
EDN: ''
},
{
id: 2,
name: "Mary May",
EDN: ''
},
{
id: 3,
name: "Christine Lobowski",
EDN: ''
},
{
id: 4,
name: "Brendon Philips",
EDN: ''
},
{
id: 5,
name: "Margret Marmajuke",
EDN: ''
},
{
id: 6,
name: "Frank Harbours",
EDN: ''
},
];
const table = new Tabulator("#example-table", {
data: tabledata,
selectable: true,
columns: [{
title: "ID",
field: "id"
},
{
title: "Name",
field: "name"
},
{
title: "EDN",
field: "EDN",
}
]
});
<!DOCTYPE html>
<html>
<head>
<!-- Tabulator CDN -->
<link href="https://unpkg.com/tabulator-tables#4.2.7/dist/css/tabulator.min.css" rel="stylesheet">
<script type="text/javascript" src="https://unpkg.com/tabulator-tables#4.2.7/dist/js/tabulator.min.js"></script>
</head>
<body>
<div id="example-table"></div>
</body>
</html>

Cytsocape.js can't create edges in for loop

I'm creating chart with nodes and edges. Once I created nodes, I can't create the associated edges without getting those kind of errors :
Can not create edge 5134fb65-b30f-4947-9870-cc909e293e21 with nonexistant source Peter
My code :
var myJSONdata = info;
var cy = window.cy = cytoscape({
container: document.getElementById('cy'),
boxSelectionEnabled: false,
autounselectify: true,
style: [
{
selector: 'node',
style: {
'content': 'data(id)',
'text-opacity': 0.5,
'text-valign': 'center',
'text-halign': 'right',
'shape': 'hexagon',
'label': 'data(label)',
'background-color': '#11479e'
}
},
{
selector: 'edge',
style: {
'curve-style': 'bezier',
'width': 4,
'target-arrow-shape': 'triangle',
'line-color': '#9dbaea',
'target-arrow-color': '#9dbaea'
}
}
],
// elements: {
// nodes: [
// { data: { id: 'Peter' } },
// { data: { id: 'Claire' } },
// { data: { id: 'Mike' } },
// { data: { id: 'Rosa' } }
// ],
// edges: [
// { data: { source: 'Peter', target: 'Claire' } },
// { data: { source: 'Claire', target: 'Mike' } },
// { data: { source: 'Mike', target: 'Rosa' } }
// ]
// }
});
var array = [];
// Create nodes
for (var i = 0; i <= myJSONdata.length - 1; i++) {
array.push({
group: 'nodes',
data: {
id: i,
label: myJSONdata[i].name
}
}
);
}
// Create edges
for (var i = 0; i <= myJSONdata.length - 1; i++) {
var source = myJSONdata[i].name;
array.push({
group: 'edges',
data: {
source: source,
target: myJSONdata[i].next_op_name
}
});
}
cy.add(array);
cy.layout({
name: 'circle'
}).run();
The "Create nodes" part is working, but the "Create edges" is not.
I tried the solution here but it does not work.
Actually I want to read data from JSON file to create the chart.
I can do it with :
elements: {
nodes: [
{ data: { id: 'Peter' } },
{ data: { id: 'Claire' } },
{ data: { id: 'Mike' } },
{ data: { id: 'Rosa' } }
],
edges: [
{ data: { source: 'Peter', target: 'Claire' } },
{ data: { source: 'Claire', target: 'Mike' } },
{ data: { source: 'Mike', target: 'Rosa' } }
]
}
But I want to automate it according to the JSON file in input.
This is my JSON file :
info = [
{
"name": "Peter",
"next_op_name": "Claire",
}, {
"name": "Claire",
"next_op_name": "Mike",
}, {
"name": "Mike",
"next_op_name": "Rosa",
}, {
"name": "Rosa",
"next_op_name": "Peter",
}
];
I can't understand what is wrong.
The source and target fields in the edge are the IDs of nodes, not labels.
When you create the nodes, you need to set id to myJSONdata[i].name as well.

Get Data from previous row

I am trying to get the previous row's data when I click on a row, and haven't been very successful at it.
As an example...If I click on the row that contains "PersonB", then I should get the previous row's value from the FirstName column, which would be PersonA.
In the change event of the grid, you can see I was trying to use prev(), but all that was being returned was an object and not sure how to get the value that I need from that prev().
$(document).ready(() => {
var data = [{
ID: 1,
FirstName: "PersonA",
LastName: "123"
},
{
ID: 2,
FirstName: "PersonB",
LastName: "456"
},
{
ID: 3,
FirstName: "PersonC",
LastName: "789"
}
];
$("#GridList").kendoGrid({
dataSource: {
data: data
},
schema: {
model: {
fields: {
ID: {
type: "number"
},
FirstName: {
type: "string"
},
LastName: {
type: "string"
}
}
}
},
filterable: false,
columns: [{
field: "ID",
title: "ID",
hidden: true
},
{
field: "FirstName",
title: "FirstName"
},
{
field: "LastName",
title: "LastName"
}
],
scrollable: true,
sortable: true,
pageable: false,
selectable: "row",
reorderable: false,
groupable: false,
resizable: true,
columnMenu: false,
dataBound: function() {
//var grid = $("#GridList").data("kendoGrid");
//for (var i = 0; i < grid.columns.length; i++) {
// grid.autoFitColumn(i);
//}
},
change: function(e) {
$('#Result').text();
//var row = $(this).closest('tr');
//var prev = row.prev();
//console.log(prev);
},
height: 200
});
});
#Result {
font-size: 36px;
}
<link href="https://kendo.cdn.telerik.com/2018.1.221/styles/kendo.common.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2018.1.221/styles/kendo.rtl.min.css">
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2018.1.221/styles/kendo.default.min.css">
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2018.1.221/styles/kendo.mobile.all.min.css">
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2018.1.221/js/angular.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2018.1.221/js/jszip.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2018.1.221/js/kendo.all.min.js"></script>
<div id="GridList"></div>
<label id='Result'></label>
You can do it like this:
change: function(e) {
$('#Result').text();
var data = this.dataItem(this.select().prev());
console.log(data);
}
Which would give you the following object when you click on PersonB:
{
"ID": 1,
"FirstName": "PersonA",
"LastName": "123"
}
$(document).ready(() => {
var data = [{
ID: 1,
FirstName: "PersonA",
LastName: "123"
},
{
ID: 2,
FirstName: "PersonB",
LastName: "456"
},
{
ID: 3,
FirstName: "PersonC",
LastName: "789"
}
];
$("#GridList").kendoGrid({
dataSource: {
data: data
},
schema: {
model: {
fields: {
ID: {
type: "number"
},
FirstName: {
type: "string"
},
LastName: {
type: "string"
}
}
}
},
filterable: false,
columns: [{
field: "ID",
title: "ID",
hidden: true
},
{
field: "FirstName",
title: "FirstName"
},
{
field: "LastName",
title: "LastName"
}
],
scrollable: true,
sortable: true,
pageable: false,
selectable: "row",
reorderable: false,
groupable: false,
resizable: true,
columnMenu: false,
dataBound: function() {
//var grid = $("#GridList").data("kendoGrid");
//for (var i = 0; i < grid.columns.length; i++) {
// grid.autoFitColumn(i);
//}
},
change: function(e) {
$('#Result').text();
var selected = this.dataItem(this.select().prev());
console.log(selected);
},
height: 200
});
});
#Result {
font-size: 36px;
}
<link href="https://kendo.cdn.telerik.com/2018.1.221/styles/kendo.common.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2018.1.221/styles/kendo.rtl.min.css">
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2018.1.221/styles/kendo.default.min.css">
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2018.1.221/styles/kendo.mobile.all.min.css">
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2018.1.221/js/angular.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2018.1.221/js/jszip.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2018.1.221/js/kendo.all.min.js"></script>
<div id="GridList"></div>
<label id='Result'></label>
You'll have to check for the use case when the row selected is the first one but here's somecode that works (see demo below)
change: function(e) {
var selectedRows = this.select();
previousPerson = $(selectedRows).prev().find('td:nth-child(2)').text();
$('#Result').text(previousPerson);
},
$(document).ready(() => {
var data = [{
ID: 1,
FirstName: "PersonA",
LastName: "123"
},
{
ID: 2,
FirstName: "PersonB",
LastName: "456"
},
{
ID: 3,
FirstName: "PersonC",
LastName: "789"
}
];
$("#GridList").kendoGrid({
dataSource: {
data: data
},
schema: {
model: {
fields: {
ID: {
type: "number"
},
FirstName: {
type: "string"
},
LastName: {
type: "string"
}
}
}
},
filterable: false,
columns: [{
field: "ID",
title: "ID",
hidden: true
},
{
field: "FirstName",
title: "FirstName"
},
{
field: "LastName",
title: "LastName"
}
],
scrollable: true,
sortable: true,
pageable: false,
selectable: "row",
reorderable: false,
groupable: false,
resizable: true,
columnMenu: false,
dataBound: function() {
//var grid = $("#GridList").data("kendoGrid");
//for (var i = 0; i < grid.columns.length; i++) {
// grid.autoFitColumn(i);
//}
},
change: function(e) {
var selectedRows = this.select();
selectedPerson = $(selectedRows).find('td:nth-child(2)').text();
previousPerson = $(selectedRows).prev().find('td:nth-child(2)').text();
//console.log(previousPerson);
$('#Result').text(previousPerson);
},
height: 200
});
});
#Result {
font-size: 36px;
}
<link href="https://kendo.cdn.telerik.com/2018.1.221/styles/kendo.common.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2018.1.221/styles/kendo.rtl.min.css">
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2018.1.221/styles/kendo.default.min.css">
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2018.1.221/styles/kendo.mobile.all.min.css">
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2018.1.221/js/angular.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2018.1.221/js/jszip.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2018.1.221/js/kendo.all.min.js"></script>
<div id="GridList"></div>
<label id='Result'></label>
A possible solution would find the index of the current selection and then fetch the index - 1 from the data array:
$(document).ready(() => {
var data = [{
ID: 1,
FirstName: "PersonA",
LastName: "123"
},
{
ID: 2,
FirstName: "PersonB",
LastName: "456"
},
{
ID: 3,
FirstName: "PersonC",
LastName: "789"
}
];
$("#GridList").kendoGrid({
dataSource: {
data: data
},
schema: {
model: {
fields: {
ID: {
type: "number"
},
FirstName: {
type: "string"
},
LastName: {
type: "string"
}
}
}
},
filterable: false,
columns: [{
field: "ID",
title: "ID",
hidden: true
},
{
field: "FirstName",
title: "FirstName"
},
{
field: "LastName",
title: "LastName"
}
],
scrollable: true,
sortable: true,
pageable: false,
selectable: "row",
reorderable: false,
groupable: false,
resizable: true,
columnMenu: false,
dataBound: function() {
//var grid = $("#GridList").data("kendoGrid");
//for (var i = 0; i < grid.columns.length; i++) {
// grid.autoFitColumn(i);
//}
},
change: function(e) {
var data = this.dataSource.data();
var selectedRows = this.select();
if(selectedRows.length > 0) {
var dataItem = this.dataItem(selectedRows[0]);
console.log('Selected ' + dataItem.FirstName);
var index = -1;
for(var i = 0; i < data.length; i++) {
if(data[i].FirstName === dataItem.FirstName) {
index = i;
}
}
if(index >0) {
dataItem = data[index -1];
console.log('Previous ' + dataItem.FirstName);
}
}
},
height: 200
});
});
#Result {
font-size: 36px;
}
<link href="https://kendo.cdn.telerik.com/2018.1.221/styles/kendo.common.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2018.1.221/styles/kendo.rtl.min.css">
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2018.1.221/styles/kendo.default.min.css">
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2018.1.221/styles/kendo.mobile.all.min.css">
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2018.1.221/js/angular.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2018.1.221/js/jszip.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2018.1.221/js/kendo.all.min.js"></script>
<div id="GridList"></div>
<label id='Result'></label>

How to make inner object in object using recursive code in javascript

I have some object type data.
Each object have same key, children.
children can have another children.
const testColumns = {
label: '테스트 수',
width: 320,
children: [
{
label: '1-1111',
width: 160,
children: [
{
key: 'testCnt',
label: '2-3333',
width: 80,
},
{
key: 'exceptionCnt',
label: '2-4444',
width: 80,
children: [
{
key: 'allTestCnt',
label: '3-5555',
width: 80,
},
{
key: 'allExceptionCnt',
label: '3-6666',
width: 80,
},
]
}
]
}
]
};
I have to make other object from testColumns to rearranged object, returnColumns.
like this.
let returnColumns = [];
testColumns.map((obj)=>{
if(obj.children){
obj.children.map((child, firstChildIndex)=>{
returnColumns['children'] = [];
returnColumns.push({
property: child.key,
header: {
label: child.label,
},
props: {
style: {
width: child.width
}
});
if(child.children){
returnColumns[firstChildIndex]['children'] = [];
child.children.map((secondChild, secondChildIndex)=>{
returnColumns[firstChildIndex]['children'].push({
property: secondChild.key,
header: {
label: secondChild.label,
},
props: {
style: {
width: secondChild.width
}
});
})
}
});
}
})
I try to make above code to recursive function. like this.
function recursiveIteration(object, callback) {
for (let property in object) {
if (object.hasOwnProperty(property)) {
if (typeof object[property] == "object"){
recursiveIteration(object[property]);
// ...
// ...
}
}
}
}
But I don't know how work this.
Above code is sample. It's not perfect.
Here is jsfiddle link
Here is what I want result
const test = {
property: undefined,
header : {
label: 'TEST1'
},
props: {
style: {
width: 320,
}
},
children: [
{
property: 'test',
header : {
label: 'test'
},
props: {
style: {
width: 160,
}
},
},
{
property: undefined,
header : {
label: '2-4444'
},
props: {
style: {
width: 160,
}
},
children: [
{
property: 'allTestCnt',
header : {
label: '3-5555'
},
props: {
style: {
width: 80,
}
},
},
{
property: 'allExceptionCnt',
header : {
label: '3-6666'
},
props: {
style: {
width: 80,
}
},
}
]
}
]
};
}
You could use a recursive callback for mapping values of the array.
var testColumns = { label: '테스트 수', width: 320, children: [{ label: '1-1111', width: 160, children: [{ key: 'testCnt', label: '2-3333', width: 80, }, { key: 'exceptionCnt', label: '2-4444', width: 80, children: [{ key: 'allTestCnt', label: '3-5555', width: 80, }, { key: 'allExceptionCnt', label: '3-6666', width: 80, }, ] }] }] },
result = [testColumns].map(function iter(o) {
var temp = {
property: undefined,
header: { label: o.label },
props: { style: { width: o.width } }
};
if (o.children) {
temp.children = o.children.map(iter);
}
return temp;
})[0];
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Categories

Resources