I have a Kendo UI Grid and I am populating and maintaining the data it displays using Knockout JS (with knockout-kendo.min.js and knockout.mapping-latest.js). When the underlying data updates, the grid also updates to reflect this change. It's working well apart from the problem outlined below.
Code presented in the following Fiddle: http://jsfiddle.net/rTtS9/
The problem is that when the grid updates, it 'forgets' the selected cell that the user has chosen, such that if they are trying to keep an eye on a certain cell value, they can't. If this data is updating sub second (which it could), this gets very silly. The are many other use-case problems too (this is a contrived one).
Is there a way to have the Kendo UI Grid avoid a complete redraw when new data arrives such that the user's selection does not get forgotten?
I thought that this issue might be because KO thought that the whole object had changed, so rather than updating an existing object, it removed and added new ones. To make sure that this isn't the case, I uniquely identify objects using “keys” via the Mapping plugin. In addition, the array remain the same length.
I think that the mapping plugin is working OK as I seem to get desired behavior with the foreach binding, whereby you can select and highlight the ID part of the list item and it won't drop your selection when the data updates. See the Fiddle to see what I mean.
In case this is helpful for anyone else, I have included my solution below which remembers which grid cells were selected before the grid is re-drawn/bound.
I have attached the following code to the Kendo Grid change and dataBound events, respectively. Note, naming conversions for my grid variables always lead with "grid" followed by "name", such as "gridName".
So for the change event:
function saveGridSelection (gridID) {
try {
var shortName = gridID.substring(4,gridID.length)
var idxGrid = ns.grids.map(function(e) {return e.name}).indexOf(shortName);
var gridID = "#grid" + shortName;
var pair=[];
var columnHeader=[];
ns.grids[idxGrid].selectedCells = [];
// Loop over selected realized volsz
$(gridID + " > .k-grid-content .k-state-selected").each(function (index, elem) {
var grid = $(gridID).data("kendoGrid");
var row = $(this).closest("tr");
var colIdx = $("td", row).index(this);
pair[index] = $('td:first', row).text();
columnHeader[index] = $(gridID).find('th').eq(colIdx).text();
if (colIdx != 0 && ns.grids[idxGrid].dataGrid.length > 0 ) { // Check if cell is permitted and has data
pairID = ns.grids[idxGrid].dataGrid.map(function(e) { return e.pair; }).indexOf(pair[index]); // Get the index for the appropriate Pair
ns.grids[idxGrid].selectedCells.push({pair: pairID, container: (colIdx - 1), pairTitle: pair[index], columnHeader: columnHeader[index] });
}
});
} catch (err) {
console.log(err);
}
}
And for the dataBound event:
function loadGridSelection (gridID) {
try {
var shortName = gridID.substring(4,gridID.length)
var idxGrid = ns.grids.map(function(e) {return e.name}).indexOf(shortName);
var gridID = "#grid" + shortName;
var grid = ns.grids[idxGrid];
var gridSelectedCells = grid.selectedCells;
var tempSelectedCells = gridSelectedCells.slice(0); // Create a temp. array to work with
$(gridID + " > div.k-grid-content > table > tbody > tr").each(function (i,e) {
var pair = $("td:nth-child(1)", this).text();
if (tempSelectedCells && typeof tempSelectedCells !== "undefined") {
var ii = tempSelectedCells.length;
while(ii--) { // Loop backwards through teh array so we can slice out the bits we're finished with.
if (pair == tempSelectedCells[ii].pairTitle) {
var row = i;
var column = tempSelectedCells[ii].container;
var noColumns = $(gridID + " > div.k-grid-content > table").find("tr:first td").length;
var cell = (row * noColumns) + 1 + column;
$(gridID).data("kendoGrid").select(gridID + " td:eq("+cell+")");
tempSelectedCells.splice(ii, 1)
}
}
}
});
} catch (err) {
console.log(err);
}
}
Improvements to code always welcome.
Related
I've been trying to find a good match to my question, but nothing really concrete. I'm still learning and don't know exactly what I'm missing.
So my code can be found here: Fiddle
This is a simplified version of what I'm working with. In the final version, I will upload a csv file to the html table you see there (id="dvCSV"). Upon uploading, the table will look like it is shown (with added dropdowns and a column of checkboxes). The checkboxes come "pre-chcecked" when I generate them but what I want is the user to be able to turn "off" the rows that I do not want to calculate on.
I'll run you through the process:
This function reads the columns that the user designates. I don't know which column they will upload the data into.
function CheckLocations() {
//Checks the uploaded data for the locations of the Lat/Lon Data based on user dropdowns
colLocs[0] = ($('#Value_0 :selected').text());
colLocs[1] = ($('#Value_1 :selected').text());
colLocs[2] = ($('#Value_2 :selected').text());
colLocs[3] = ($('#Value_3 :selected').text());
LatColumn = colLocs.indexOf("Lat");
LongColumn = colLocs.indexOf("Long");
}
function AllTheSame(array) { //if they do not designate the checkboxes, I prompt them to
var first = array[0];
return array.every(function (element) {
return element === first;
});
}
This function takes all of the data in the designated columns and places them into an array for calculation.
function data2Array() {
//gets the lat and long data from the assigned columns and transfers them to an array for calculation
$("#dvCSV tr td:nth-child(" + (LatColumn + 1) + ")").each(function () {
var tdNode = $("<td/>");
tdNode.html(this.innerHTML);
LatData.push(tdNode.text());
});
LatData.splice(0, 2);
LatData.unshift(1, 1);
$("#dvCSV tr td:nth-child(" + (LongColumn + 1) + ")").each(function () {
var tdNode = $("<td/>");
tdNode.html(this.innerHTML);
LongData.push(tdNode.text());
});
LongData.splice(0, 2); //these two lines remove the first two items then replace them with 0
LongData.unshift(1, 1);
}
The first of these functions removes the checkbox column after calculations are done then new calculated columns are appended at the end. The second one was my attempt to read the checkboxes into an array. Ideally I'd want an array of values true or false, then do the calculations and return the calculated values back to the dvCSV table. For the td's where no calculation was performed, the cell would be empty.
function removeChecks() {
$("#dvCSV th:last-child, #dvCSV td:last-child").remove();
}
function makeCheckArray() {
var searchIDs = $("#dvCSV tbody td:last() input:checkbox:checked").map(function () {
return $(this).val();
}).get();
alert(searchIDs);
}
Hopefully I made the problem clear. Any help would be appreciated.
Pass a class when your table is generated into the tr element. Then create an on change method for your checkboxes. Read more here: http://api.jquery.com/on/
Also if you cannot get the inserted rows id's from your table then start a counter outside of your js like this
counter = 0;
Then inside of your loop add counter++
SO..
<tr class="row-1">
<td>
</td>
</tr>
Then add this snippet outside all of your other JS
$( "tr" ).on( "change", function() {
//do something
$(this+'.row-'+(counter)).hide();
});
This should get you headed in the right direction.
Okay, so we have some legacy code which uses Kendo UI Grids.
After sorting the grid, we need to be able to read the DataSource item which corresponds to each row, by iterating through the JQuery selected 'tr' list and then select the DataSource item based on the index of the row itself.
The problem exists in that the DataSource doesn't sort when the grid sorts, so you cannot simply get the index of each row and look up the corresponding DataSource item, like this...
$('td:nth-child(' + colIndex + ')', $('tbody', grid.element).eq(0)).each(
function (iIndex) {
var td = $(this);
var tr = td.parent();
var data = grid.dataSource.data()[iIndex];
if (data.Status.toLowerCase() !== 'c') {
totalBalanceDue = (totalBalanceDue - data.Payment) > 0 ? (totalBalanceDue - data.Payment) : 0;
};
td.html('$' + totalBalanceDue.formatMoney(2, '.', ','));
}
);
This is all not needed. All you need to use is the view() method of the dataSource.
Looks like I have to answer this question myself.
I have found, by scouring the documentation and the web, that the way I'm approaching this is not necessarily accurate. Instead of attempting to sort the array to match the rows of the gridview, I can use the data-uid attribute of the row, to get the corresponding dataitem from the DataSource.data() array, by using the dataSource.getByUid() function.
This is working just as I need it to.
$('td:nth-child(' + colIndex + ')', $('tbody', grid.element).eq(0)).each(
function (iIndex) {
var td = $(this);
var tr = td.parent();
//gets the corresponding dataitem for the selected row.
var data = grid.dataSource.getByUid(tr.data("uid"));
if (data.Status.toLowerCase() !== 'c') {
totalBalanceDue = (totalBalanceDue - data.Payment) > 0 ? (totalBalanceDue - data.Payment) : 0;
};
td.html('$' + totalBalanceDue.formatMoney(2, '.', ','));
}
);
I have a textbox that comma separated/delimited values are entered into which I have to make sure has unique entries. Solved that using Paul Irish's Duck Punching example #2 and tying it to onblur for that textbox.
The values entered into the textbox get broken out into a table. As the table can get very lengthy, I found Mottie's Tablesorter to work brilliantly.
The problem is, the the Duck Punching code is breaking the Tablesorter. The style for the Tablesorter is passed through just fine, but the table doesn't actually sort. BUT, when I comment out the Duck Punching code, Tablesorter miraculosly works.
My coding skills are not such that I can figure out why the two are conflicting. Any assistance would be much appreciated.
I haven't modified the Tablesorter code or added any special sorting elements to it...just following the very basic example right now. Here's the Duck Punching code which I've only modified to include the var for the textbox I need to have unique entries.
function ValidateTextBox1()
{
(function($){
var arr = document.getElementById("TextBox1").value.split(',');
var _old = $.unique;
$.unique = function(arr){
// do the default behavior only if we got an array of elements
if (!!arr[0].nodeType){
return _old.apply(this,arguments);
} else {
// reduce the array to contain no dupes via grep/inArray
return $.grep(arr,function(v,k){
return $.inArray(v,arr) === k;
});
}
};
})(jQuery);
}
The function above is in a separate js file which is called via onblur for TextBox1.
Then, I have a button which runs the following:
function GenerateTable()
{
var Entry1 = document.getElementById("TextBox1").value
var Entry2 = document.getElementById("TextBox2").value
var content = "<table id=myTable class=tablesorter ><thead><tr><th>Entry 1 Values</th><th>Entry 2 Value</th></tr></thead><tbody>"
var lines = Entry1.split(","),
i;
for (i = 0; i < lines.length; i++)
content += "<tr><td>" + (Entry1.split(",")[i]) + "</td><td>" + Entry2 + "</td></tr>";
content += "</tbody></table>"
$("#here_table").append(content);
$(function(){
$("#myTable").tablesorter({
theme: 'default'
});
});
}
The function will generate/append the table in a specific DIV.
If I leave in the validation code for TextBox1, the table will generate but isn't sortable (though it does manage to still pull the theme).
If I remove the validation code, the table will generate and is sortable.
The validateText box function above will not work as expected. In this case, "duck-punching" is not even necessary.
Here is how I would fix the script (demo):
HTML
<textarea id="textbox1">6,1,7,5,3,4,3,2,4</textarea><br>
<textarea id="textbox2">column 2</textarea><br>
<button>Build Table</button>
<div id="here_table"></div>
Script (requires jQuery 1.7+)
(function($) {
// bind to button
$(function () {
$('button').on('click', function () {
// disable button to prevent multiple updates
$(this).prop('disabled', true);
generateTable();
});
});
function unique(arr) {
return $.grep(arr, function (v, k) {
return $.inArray(v, arr) === k;
});
}
function generateTable() {
var i,
$wrap = $('#here_table'),
// get text box value, remove unwanted
// spaces/tabs/carriage returns & create an array
val = $('#textbox1').val().split(/\s*,\s*/),
// get unique values for Entry1
entry1 = unique( val ),
entry2 = $('#textbox2').val(),
content = "";
// build tbody rows
for (i = 0; i < entry1.length; i++) {
content += "<tr><td>" + (entry1[i] || '?') + "</td><td>" + entry2 + "</td></tr>";
}
// update or create table
if ($wrap.find('table').length) {
// table exists, just update the data
$wrap.find('tbody').remove();
$wrap.find('table')
.append(content)
.trigger('update');
} else {
// table doesn't exist, build it from scratch
$wrap
.html('<table id=myTable class=tablesorter><thead><tr>' +
'<th>Entry 1 Values</th>' +
'<th>Entry 2 Value</th>' +
'</tr></thead><tbody>' + content + '</tbody></table>')
.find('table')
.tablesorter({
theme: 'blue'
});
}
// enable the button to allow updating the table
$('button').prop('disabled', false);
}
})(jQuery);
I tried to add a few comments to make more clear what each step is doing. Please feel free to ask for any clarification.
I have a scenario with grid within grid implemented using the detailInit method. Here when user makes edit, i do some calculations that will change the data in the both parent and child. and then to refresh data, i will call the datasource.read to render data. this works and the data is displayed, however any detail grid which are expanded will be collapsed, is there any way i can prevent this from happening.
To answer this and another question:
"I figured out how to set the data in the master from the child BUT, the
whole table collapses the child grids when anything is updated, this is a
very annoying behavior, is there anyway I can just update a field in
the master table without it collapsing all the child elements?
(basically, update the column, no mass table update)"
in another thread at: telerik
This is extremely annoying behavior of the Kendo Grid and a major bug. Since when does a person want the sub-grid to disappear and hide a change that was just made! But this isn't the only problem; the change function gets called a Fibonacci number of times, which will freeze the browser after a significant number of clicks. That being said, here is the solution that I have come up with:
In the main grid
$('#' + grid_id).kendoGrid({
width: 800,
...
detailExpand: function (e) {
var grid = $('#' + grid_id).data("kendoGrid");
var selItem = grid.select();
var eid = $(selItem).closest("tr.k-master-row").attr('data-uid')
if (contains(expandedItemIDs, eid) == false)
expandedItemIDs.push(eid);
},
detailCollapse: function (e) {
var grid = $('#' + grid_id).data("kendoGrid");
var selItem = grid.select();
var eid = $(selItem).closest("tr.k-master-row").attr('data-uid')
for (var i = 0; i < expandedItemIDs.length; i++)
if (expandedItemIDs[i] == eid)
gridDataMap.expandedItemIDs.splice(i, 1);
},
Unfortunately globally we have:
function subgridChange() {
var grid = $('#' + grid_id).data("kendoGrid");
for (var i = 0; i < expandedItemIDs.length; i++)
grid.expandRow("tr[data-uid='" + expandedItemIDs[i] + "']");
}
function contains(a, obj) {
for (var i = 0; i < a.length; i++)
if (a[i] === obj) return true;
return false;
}
expandedItemIDs = [];
Now the 'subgridChange()' function needs to be called every time a change is made to the subgrid.
The problem is that the number of times the change function in the subgrid gets called increases exponentially on each change call. The Kendo grid should be able to call a stop propagation function to prevent this, or at least give the programmer access to the event object so that the programmer can prevent the propagation. After being completely annoyed, all we have to do is to place the 'subgridChange()' function in the subgrid 'datasource' like so:
dataSource: function (e) {
var ds = new kendo.data.DataSource({
...
create: false,
schema: {
model: {
...
}
},
change: function (e) {
subgridChange();
}
});
return ds;
}
I also had to place the 'subgridChange()' function in the Add button function using something like this
$('<div id="' + gridID + '" data-bind="source: prodRegs" />').appendTo(e.detailCell).kendoGrid({
selectable: true,
...
toolbar: [{ template: "<a class='k-button addBtn' href='javascript://'><span class='k-icon k-add' ></span> Add Product and Region</a>" }]
});
$('.addBtn').click(function (event) {
...
subgridChange();
});
When a user selects a row, record the index of the selected row. Then after your data refresh, use the following code to expand a row
// get a reference to the grid widget
var grid = $("#grid").data("kendoGrid");
// expands first master row
grid.expandRow(grid.tbody.find(">tr.k-master-row:nth-child(1)"));
To expand different rows, just change the number in the nth-child() selector to the index of the row you wish to expand.
Actually all that is needed is the 'subgridChange()' function in the main grid 'dataBound' function:
$('#' + grid_id).kendoGrid({
...
dataBound: function (e) {
gridDataMap.subgridChange();
}
});
Different but similar solution that i used for same problem:
expandedItemIDs = [];
function onDataBound() {
//expand rows
for (var i = 0; i < expandedItemIDs.length; i++) {
var row = $(this.tbody).find("tr.k-master-row:eq(" + expandedItemIDs[i] + ")");
this.expandRow(row);
}
}
function onDetailExpand(e) {
//refresh the child grid when click expand
var grid = e.detailRow.find("[data-role=grid]").data("kendoGrid");
grid.dataSource.read();
//get index of expanded row
$(e.detailCell).text("inner content");
var row = $(e.masterRow).index(".k-master-row");
if (contains(expandedItemIDs, row) == false)
expandedItemIDs.push(row);
}
function onDetailCollapse(e) {
//on collapse minus this row from array
$(e.detailCell).text("inner content");
var row = $(e.masterRow).index(".k-master-row");
for (var i = 0; i < expandedItemIDs.length; i++)
if (expandedItemIDs[i] == row)
expandedItemIDs.splice(i, 1);
}
function contains(a, obj) {
for (var i = 0; i < a.length; i++)
if (a[i] === obj) return true;
return false;
}
I am trying to create a cfgrid (Coldfusion 9) with locked columns.
I looked at the code at http://dev.sencha.com/deploy/ext-4.0.0/examples/grid/locking-grid.html and can see that the property I need to set is 'locked' = true...
here is the javascript code:
<cfsavecontent variable="headContent">
<script type="text/javascript">
function init()
{
var myGrid = ColdFusion.Grid.getGridObject('gridData');
//turn on the grid panel's lockable option - not sure if this is needed or not
myGrid.lockable = true;
//get the column model
cm = myGrid.getColumnModel();
//lock the first two columns in the grid
for(var i=0; i < 2; i++) {
var thisid = cm.getColumnId(i);
var thiscol = cm.getColumnById(thisid);
thiscol.locked = true;
//for (prop in thiscol){ document.write("object." + prop + " = " + thiscol[prop] + "<br>");}
}
//refresh the grid
ColdFusion.Grid.refresh('gridData',false);
}
</script>
</cfsavecontent>
I don't get any errors..but don't get my locked columns either.
I know I can affect the properties of the grid using this particular javascript code - I tried setting thiscol.sortable = false and that did indeed grey out the ability to sort the column.
any ideas??
I solved my problem by downloading extjs 4 and creating the js code needed..