How to get the displayed data of KendoGrid in json format? - javascript

I have a kendoGrid and i would like to get the JSON out of it after filtering and sorting how do I achieve this?
something like the following,
var grid = $("#grid").data("kendoGrid");
alert(grid.dataSource.data.json); // I could dig through grid.dataSource.data and I see a function ( .json doen't exist I put it there so you know what i want to achieve )
Thanks any help is greatly appreciated!

I think you're looking for
var displayedData = $("#YourGrid").data().kendoGrid.dataSource.view()
Then stringify it as follows:
var displayedDataAsJSON = JSON.stringify(displayedData);
Hope this helps!

If you want to get all pages of the filtered data you can use this:
var dataSource = $("#grid").data("kendoGrid").dataSource;
var filters = dataSource.filter();
var allData = dataSource.data();
var query = new kendo.data.Query(allData);
var data = query.filter(filters).data;
Make sure to check if filters exist before trying to apply them or Kendo will complain.

To get count of all rows in grid
$('#YourGridName').data("kendoGrid").dataSource.total()
To get specific row items
$('#YourGridName').data("kendoGrid").dataSource.data()[1]
To get all rows in grid
$('#YourGridName').data("kendoGrid").dataSource.data()
Json to all rows in grid
JSON.stringify($('#YourGridName').data("kendoGrid").dataSource.data())

For the JSON part, there's a helper function to extract the data in JSON format that can help:
var displayedData = $("#YourGrid").data().kendoGrid.dataSource.view().toJSON()
EDIT: after some errors with the above method due to kendo grid behavior, I found this article that solves the problem:
Kendo DataSource view not always return observablearray

Something like this, to display only data that is being viewed at the moment. Also extended the grid to provide these functions all over the app.
/**
* Extends kendo grid to return current displayed data
* on a 2-dimensional array
*/
var KendoGrid = window.kendo.ui.Grid;
KendoGrid.fn.getDisplayedData = function(){
var items = this.items();
var displayedData = new Array();
$.each(items,function(key, value) {
var dataItem = new Array();
$(value).find('td').each (function() {
var td = $(this);
if(!td.is(':visible')){
//element isn't visible, don't show
return;//continues to next element, that is next td
}
if(td.children().length == 0){
//if no children get text
dataItem.push(td.text());
} else{
//if children, find leaf child, where its text is the td content
var leafElement = innerMost($(this));
dataItem.push(leafElement.text());
}
});
displayedData.push(dataItem);
});
return displayedData;
};
KendoGrid.fn.getDisplayedColumns = function(){
var grid = this.element;
var displayedColumns = new Array();
$(grid).find('th').each(function(){
var th = $(this);
if(!th.is(':visible')){
//element isn't visible, don't show
return;//continues to next element, that is next th
}
//column is either k-link or plain text like <th>Column</th>
//so we extract text using this if:
var kLink = th.find(".k-link")[0];
if(kLink){
displayedColumns.push(kLink.text);
} else{
displayedColumns.push(th.text());
}
});
return displayedColumns;
};
/**
* Finds the leaf node of an HTML structure
*/
function innerMost( root ) {
var $children = $( root ).children();
while ( true ) {
var $temp = $children.children();
if($temp.length > 0) $children = $temp;
else return $children;
}
}

Related

OpenUI5 Treetable: get selected rows and their model data

For some hours now I'm trying to get the model data of selected rows of a tree table.
I used this example: https://openui5.hana.ondemand.com/#/sample/sap.ui.table.sample.TreeTable.JSONTreeBinding/preview
Additionally, I added sortProperty and filterProperty to the columns. Until now everything works.
What I want to do is to submit the json data via ajax of all selected rows. for this, I need to get the json data of the selected rows.
What I tried:
var oTable = this.getView().byId("tableName").getSelectedIndicies()
and then
for(var i=0; i<=oTable.length; i++) {
this.getView().byId("tableName").getModel().getData().jobs[oTable[i]]
}
it seems that when I use the sorter and filter function, the indicies are not correct anymore. The indicies keys won't change.
any idea how to solve my request? thx in advance!
There is a small change you can do to get the right data in your for loop.
Get the bindingContext of the item which is selected as per the indices information.
var sPath = TreeTable.getRows()[0].getBindingContext()
Get the data from the model as:
oTreeTable.getModel().getProperty(sPath)
this is how I solved it:
var oJSON = {};
var aData = [];
var oTable = this.getView().byId("TreeTable");
var aIndicies = oTable.getSelectedIndices();
var oSelect = this.getView().byId("selectStandort").getSelectedKey();
for (var i=0; i<aIndicies.length; i++) {
var oTableContext = oTable.getContextByIndex(aIndicies[i]);
var rowData = oTable.getModel("jobs").getProperty(oTableContext.getPath());
aData.push(rowData);
}
oJSON.jobs = aData;
oJSON.standort = oSelect;

How to Create javascript json multidimensional tree from flat data

Hello guys I have a problem creating JSON tree from input form. Imagine you have one section of fields and then dynamically more sections are added. To be more precise, I am talking about switch properties. I just dont know how to add key as new array and then put there more properties with values. Here is the code I am fighting with.
//FIRST section with just basic info about switch
function generateNewSwitchInDB() {
var portInfo = [];
$('#myModal').find('#inputs').find('input').each(function(){
var switchProperty = $(this)[0].id;
portInfo[switchProperty] = $(this)[0].value;
});
//SECOND section dynamically loop through new created sections and grab input id and input value
portInfo.push({'portSlots' : 'portSlot'});
$('#myModal').find('.ports').each(function(){
portInfo[0]['portSlots'][$(this)[0].id] = $(this)[0].id;
$(this).find('input').each(function(){
var placeHolder = $(this)[0].placeholder;
portInfo[0]['portSlots']['0'][placeHolder] = $(this)[0].value;
});
});
console.log(portInfo);
}
What i want to achieve should look like this, but I cant figure out how to push there new key and to that key add properties.
{
'SwitchBasicInfo':{
'location':'Munich',
'vendor':'Cisco',
'hostname':'Switch123',
},
'Slots':{
'slot1':{
'numberOfEthernetPorts':'20',
'numberOfSerialPorts':'50',
'numberOfConsolePorts':'1',
},
'slot2':{
'numberOfEthernetPorts':'50',
'numberOfSerialPorts':'2',
'numberOfConsolePorts':'1',
},
'slot3':{
'numberOfEthernetPorts':'100',
'numberOfSerialPorts':'20',
'numberOfConsolePorts':'1',
},
}
}
Ok, I figured that out, every new level must begin with an array.
First section with basic data
var newSwitchData = new Object();
newSwitchData = {'switchBasicInfo': {}};
newSwitchData.switchBasicInfo['switchProperty'] = $(this)[0].value;
Dynamic sections within foreach loop
newSwitchData.portSlots = {};
newSwitchData.portSlots['slotId'] = {};
newSwitchData.portSlots['slotId']['placeHolder'] = $(this)[0].value;

Working with Localstorage for put content in table (JQuery)

I have a big problem working with this.
I have a table in my html, in my js I'm using localstore (I have never used that before)
I insert a new row, and it is stored with localstore, I create a JSON.
For putting the ID of the raw, I just get the length of my localstorage.
For example, I have 3 rows, with IDs 1, 2 and 3.
If I decide to delete one, we can say the number 2, I can delete it, yeah, but the next time when I create a new raw I'll have the id = 2.
why?, because I use localstorage.length+1 for putting the id, so... If I had 3 before, the next time I'll get a 3, I'll replace my content where ID = 3.
what can I do for avoid that mistake?
my JS is this
crearTabla(tablastorage)
$("#btnNuevo").on('click',function(){
$("#mymodal1").modal("show");
$('#btnGuardar').data('evento','crear');
});
$("#btnCargar").on('click',function(){
crearTabla(tablastorage)
});
$("#btnGuardar").on('click',function(){
if($(this).data('evento') == "crear"){
Crear();
$('input:text').val('');
}
else{
Modificar();
}
$("#mymodal1").modal("hide");
});
function crearTabla(data){
$("#tabla").empty();
$.each(data, function(index, val){
var temp = JSON.parse(val);
var $tr = $("<tr/>");
var $tdID = crearTD(temp.id);
var $tdMatricula = crearTD(temp.matricula);
var $tdNombre = crearTD(temp.nombre);
var $tdSexo = crearTD(temp.sexo);
var $tdAccion = crearAccion(temp);
$tr.append($tdID, $tdMatricula, $tdNombre, $tdSexo, $tdAccion);
$("#tabla").append($tr);
$('input:text').val('');
})
}
function Crear(){
var $tr = $("<tr/>");
var $tdID = crearTD(tablastorage.length+1);
var $tdMatricula = crearTD($("#matricula").val());
var $tdNombre = crearTD($("#nombre").val());
var $tdSexo = crearTD($("#sexo").val());
var JSon = {
id:tablastorage.length+1,
matricula:$("#matricula").val(),
nombre:$("#nombre").val(),
sexo:$("#sexo ").val()
}
if($('#matricula').val()=='' || $('#nombre').val()=='' || $('#sexo').val()==''){
alert("Uno o mas campos vacios");
}
else{
tablastorage.setItem(tablastorage.length, JSON.stringify(JSon))
var $tdAccion = crearAccion(JSon);
crearTabla(tablastorage)
$('input:text').val('');
}
};
function crearTD(texto){
return $("<td/>").text(texto);
};
function crearAccion(objeto){
var $td = $("<td/>");
var $div = $("<div/>",{
class:'btn-group',
role:'group'
});
var $btnElminar = $("<button/>",{
class:'btn btn-danger eliminar'
}).html("<i class='glyphicon glyphicon-remove'></i>"
).data('elemento',objeto);
var $btnModificar = $("<button/>",{
class:'btn btn-info modificar'
}).html("<i class='glyphicon glyphicon-pencil'></i>"
).data('elemento',objeto);
$div.append($btnElminar, $btnModificar)
return $td.append($div);
};
$("#tabla").on('click','.eliminar',function(event){
console.log($(this).data('elemento').id)
tablastorage.removeItem($(this).data('elemento').id-1)
crearTabla(tablastorage)
});
$("#tabla").on('click','.modificar',function(event){
index = $(this).data('elemento').id-1;
var $elemento = $(this).data('elemento');
$('#btnGuardar').data('evento','modificar');
$('#id').val($elemento.id);
$('#matricula').val($elemento.matricula);
$('#nombre').val($elemento.nombre);
$('#sexo').val($elemento.sexo);
$("#mymodal1").modal("show");
});
and my html have this code:
http://notes.io/wAYL
Two extra things.
1. Sorry for my bad english, If I've made a mistake is because I speak spanish, not english all the time, I need to improve my skills with the languague.
2. Also because I don't know how to put the code here. I just tried and I faild so many times.
<-- Please don't erase this -->
What i usually do is store whole arrays in one storage key as JSON.
When you load page you get whole array using something like:
var data = JSON.parse( localStorage.getItem('tableData') || "[]");
$.each(data, function(_, item){
// append html to table for each item
});
Then in your Crear() you would push the new item into the array, and store the whole array
var JSon = {
id: +new Date(),
matricula:$("#matricula").val(),
nombre:$("#nombre").val(),
sexo:$("#sexo ").val()
}
data.push(JSon);
localStorage.setItem('tableData', JSON.stringify(data));
Similar to remove an item , splice() the array to remove it from main array and store again.
One suggestion for ID is use current timestamp

Kendo UI Grid select by data item

I have a Kendo UI Grid with a large datasource and paging.
I have an event that fires where I know the underlying data item that I want to select, but am unsure on how to programatically page/select this item in the grid. If the item is not on the current grid page, I cannot use datasource.view() to poke through when the data is not on the current page.
Does anyone know how I can select an item by its underlying data source object?
I've got a similar situation to where i am at #:
http://jsfiddle.net/Sbb5Z/1050/
I can get the data item with the following:
change: function (e) {
var selectedRows = this.select();
var dataItem = this.dataItem(selectedRows[0]);
}
But then I don't know how to select the same row in the other grid.
Basically in the select event of one grid, I want to go select the same item in another grid. These are not the same datasource, as they have different page setups, but it is the same underlying data array.
I have the data item in the target grid -- but I have no clue how to page/select it in the target grid.
Edit:
The best I've come up with sofar is creating a datasource with the same parameters as the original, and paging through it programatically, until I find what I am looking for. Surely there must be a better way?
I've gotten this back from Telerik, and is a little cleaner:
http://jsfiddle.net/RZwQ2/
function findDataItem(theGrid, dataItem) {
//get grid datasource
var ds = theGrid.dataSource;
var view = kendo.data.Query.process(ds.data(), {
filter: ds.filter(),
sort: ds.sort()
})
.data;
var index = -1;
// find the index of the matching dataItem
for (var x = 0; x < view.length; x++) {
if (view[x].Id == dataItem.Id) {
index = x;
break;
}
}
if (index === -1) {
return;
}
var page = Math.floor(index / theGrid.dataSource.pageSize());
var targetIndex = index - (page * theGrid.dataSource.pageSize()) + 1;
//page is 1-based index
theGrid.dataSource.page(++page);
//grid wants a html element. tr:eq(x) by itself searches in the first grid!
var row = $("#grid2").find("tr:eq(" + targetIndex + ")");
theGrid.select(row);
console.log('Found it at Page: ' + page + 'index: ' + targetIndex);
}
You need to have a common id, or field in the data that you can use to uniquely identify the object in the other dataSource, because the kendo generated UID's are not going to be the same accross two different DataSource instances.
Most generally you define the id in the Model you bound to the grid, which you can use to quickly pluck items from the datasource
change: function (e) {
var selectedRows = this.select();
var dataItem = this.dataItem(selectedRows[0]);
var otherItem = otherGrid.dataSource.get(dataItem.id) // will get
}
if you don't have a common ID field specified in the model, but do know how to find the item you can loop through the data source looking for it
var selectedRows = this.select();
var dataItem = this.dataItem(selectedRows[0]);
var data = otherGrid.dataSource.view();
var otherItem;
for ( var i = 0; i < data.length; i++ ){
if( data[i].myCommonField === dataItem.myCommonField ) {
otherItem = data[i];
break;
}
}
UPDATE:
to select the item in the other grid you need to do this:
var elements = otherGrid.items(),
element;
element = elements.filter("[data-uid='" + otherItem.uid + "']")
otherGrid.select(element) // to select just the one item
//OR
otherGrid.select( otherGrid.select().add(element) ) // to add the item to the current selection
I the fiddle you provided uses a really old version of kendo Grid where this won't work...I just realized. are you stuck on the 2011 version? I can probably get something to work at least in theory but the above will work in the newer versions
essentailly you need to match the item you have to a DOM element, in later versions you can use UID because the dom elements all get that on them "data-uid" it looks like if you at id to your model: { } def you can get the tr elements to have data-id which you can use to select the right select using jquery. I use the items()1 method which also doesn't seem to exist on the early version but you can usegrid2.table.find("tr[data-id=]")` instead I believe
Assume div id will be Grid then first we need find the kendoGrid
var grid = $("#Grid").data("kendoGrid");
then call the grid.select() to select the currently selected one
finally call the grid.dataItem() to get the selected item.
var selectedDataItem = grid.dataItem(grid.select());
To expand upon others, I have a method that takes a single (or multiple) ids to match against:
function selectItems(grid, idAr)
{
if(!idAr instanceof Array)idAr = [idAr];
var items = grid
.items()
.filter(function(i, el)
{
return idAr.indexOf(grid.dataItem(el).Id) !== -1;
});
grid.select(items);
}
* Obviously Id could be replaced by any field that is in your data item.
Use for selection:
selectItems(grid, "5");
selectItems(grid, ["6", "7"]);

how to get selected rows of master table and child table in jtable

here I am trying to write like this..
but this code is not working for me as i expects..
i am getting the alert message like
[{rcid:1}]
but i want alert message like this.. [{rcid:1, rdsid:10}]
Note: rcid is selected parent recordid and rdsid is selected child reord id
any ideas would be greatly appreciated.. thanks in advance..
function CheckForm() {
var $selectedRows = $('#PersonTableContainer').jtable('selectedRows');
// var $selectedChildRows = $('.jtable-child-table-container').jtable('selectedRows');
var myjson = [];
$selectedRows.each(function () {
var record = $(this).data('record');
myjson.push({
rcid: record.rcid,
rdsid: record.rdsid
});
});
$('jsondata').val(JSON.stringify(myjson)); // this will encode in a json string
alert(JSON.stringify(myjson));
return false;
}
I was trying to do something similar on my end. I was about to go crazy because I couldn't find the answer. I will first say, I'm new to jQuery so there might be a better way but I couldn't find it.
var $selectedRows = $('#PersonTableContainer').jtable('selectedRows');
returns a list of the selected rows from all the tables above it. In my case, I was 3 child tables deep. So my $selectedRows had a length of 3. I suspect yours has a length of 2.
For your situation I suggest:
var $rcid = 0;
var $rdsid = 0;
var $index = 0;
$selectedRows.each(function () {
var record = $(this).data('record');
if(index == 0){
rdsid = record.rcid;
}
if(index == 1){
rdsid = record.rdsid;
}
index++;
});
myjson.push({
rcid: $rcid,
rdsid:$rdsid
});

Categories