I have a table that gets rows added to it dynamically. Right now I have 140 rows. The visibleRowCount is set to 20 like so:
var oTable = new sap.ui.table.Table({
id: "sapTable",
title: "Table Example",
visibleRowCount: 20,
selectionMode: sap.ui.table.SelectionMode.Single
}).addStyleClass("alternate-color");
When I click on a row I want to find out the index. This is how I do it:
$("#myTable").on("tap", "tr", function (e) {
// Works until you scroll the table - Top element becomes index of 1
var index = this.rowIndex;
console.log(index);
});
Which gets the correct index for the first 20 rows but once you start scrolling the table the index of the top row becomes 1 since the sapui5 table loads the information into the table on scroll. I think I am going to have to go about this a different way. Any ideas?
I will set up a jsbin tomorrow if needed.
When a row of a table is selected/deselected, a rowSelectionChange event is fired.
var oTable = new sap.ui.table.Table({
id: "sapTable",
title: "Table Example",
visibleRowCount: 20,
selectionMode : sap.ui.table.SelectionMode.Single,
rowSelectionChange: function(e) {
var oIndex = e.getParameter('rowIndex');
if (oTable.isIndexSelected(oIndex )) {
var oContext= oTable.getContextByIndex(oIndex );
var path = oContext.sPath;
var object = oTable.getModel().getProperty(path);
console.log(object);
}
}
}).addStyleClass("alternate-color");
Above in the code, we can get the selected or deselected row; then we use the isIndexSelected function to check if it is selected or deselected. And by getting the context and path, we are able to get the binding object itself.
Please note that if row 1 is already selected and now user select row 2, this event will not fire for that deselection of row 1, an event will be fired for selection of row 2.
Hope this helps!
Related
I'm currently using the DataTables plugin for my project.
I have an AJAX sourced datatable where you can only ever have one row selected, now because my datatable is done server-side I need to keep track of which one is selected when changing pages.
Therefore I have been using this solution but this only seems to work for multiple row selection
Now essentially what I want to happen is, when you select a new row it should add the new row id to the array but also remove the previously added row id from the array, so there should only ever be one result in the array at a time.
Visually for better understanding:
var selected = []
Click Row 1 after loading table = [row_1]
Click Row 2 removing row_1 and adding row_2 = [row_2]
var selected = [];
$("#example").DataTable({
"processing": true,
"serverSide": true,
"ajax": "scripts/ids-arrays.php",
"rowCallback": function( row, data ) {
if ( $.inArray(data.DT_RowId, selected) !== -1 ) {
$(row).addClass('selected');
}
}
});
$('#example tbody').on('click', 'tr', function () {
var id = this.id;
var index = $.inArray(id, selected);
if ( index === -1 ) {
selected.push( id );
} else {
selected.splice( index, 1 );
}
$(this).toggleClass('selected');
} );
Instead of adding an element to the array, you could replace the whole array. It seems a bit wasteful to use an array to store a single element, but there you go.
selected.push( id );
becomes
selected = [id];
I'm using the DataTables library to create a table with extra functionality. What I'd like to achieve, is that the user can select rows and then press a button. This will call the server, do some stuff and the rows should be updated accordingly.
However, after I'm done iterating over the rows to be changed and setting its values, re-drawing the table does not actually update its values. I update the data object, invalidate the cache and call table.draw(). It's very similar to the last example on this page.
I have created a JSFiddle of this issue. The button updates the date objects of the selected rows and the table is re-drawn, but the data inside the table is not updated. The core JS code:
$('#updateRow').click(function() {
//Get the table
var table = $('#example').DataTable();
//Iterate over selected rows
var rowData = table.rows({
selected: true
}).every(function() {
//For every selected row, update startDate
var d = this.data();
d.startDate = "01/01/2017";
console.log('Set startDate of ' + d.name + ' to ' + d.startDate);
//Invalidate the cache
this.invalidate();
});
//Re-draw the table
table.draw();
});
I forked and did the solution from your JsFiddle. Here's the relevant snippet from fiddle https://jsfiddle.net/k38r9be5/1/
var rowData = table.rows({
selected: true
}).every(function(rowIdx) {
var colIdx = 4; // startDate is the fifth column, or "4" from 0-base (0,1,2,3,4...)
table.cell( rowIdx, colIdx).data('01/01/2017').draw();
});
Basically, via the API you can get the cell object itself, and modify the contents with .data(). In your version you weren't actually getting a particular cell object and instead just copied the data contents of the row to a variable, and modified that.
I have the following Problem:
I want to dynamically create table rows and cells with different settings.
The Solution mentioned here: Dynamic binding of table column and rows
was a good starting point for my problem, but I still could not get it to work.
The table should display each object of the model in a new row with the binding for the given attributes of that object.
The checked attribute should be displayed in/as a checkbox that is either checked or unchecked depending on the value (true or false) of checked.
Now, this works perfectly fine if I define the bindings and columns as they are in the SAPUI5 Table Example
The Problem:
Depending on value (true or false) of the objects existsLocal attribute I want the checkbox of that row to be either enabled or disabled. Further that row should get a new class - called existsLocalClass wich sets its background to grey if existsLocal is true.
I was thinking that this can be solved with a factory function that creates my rows and its cells. Unfortunately my factory does not work as intended.
Here is my code:
Model definition:
var model = [
{name: "name1", description: "description1", checked: true, existsLocal: true},
{name: "name2", description: "description2", checked: false, existsLocal: false}
]
var oModel = new sap.ui.model.json.JSONModel();
oModel.setData({modelData: model});
Table plus factory function:
var oTable = new sap.ui.table.Table({
visibleRowCount: 7,
firstVisibleRow: 3,
selectionMode: sap.ui.table.SelectionMode.None
});
var tableRowFactory = function (sId, oContext) {
console.log("row factory");
var exists = oContext.getProperty("existsLocal");
if(exists){
return new sap.ui.table.Row(sId)
.addCell(new sap.ui.commons.TextView()
.bindProperty("text", oContext.sPath + "/name"))
.addCell(new sap.ui.commons.TextView()
.bindProperty("text", oContext.sPath+ "/description"))
.addCell(new sap.ui.commons.CheckBox()
.bindProperty("checked", oContext.sPath+ "/checked").setEnabled(false))
.addStyleClass("existsLocal");
}else{
return new sap.ui.table.Row(sId)
.addCell(new sap.ui.commons.TextView()
.bindProperty("text", oContext.sPath + "/name"))
.addCell(new sap.ui.commons.TextView()
.bindProperty("text", oContext.sPath+ "/description"))
.addCell(new sap.ui.commons.CheckBox()
.bindProperty("checked", oContext.sPath+ "/checked"))
}
};
oTable.setModel(oModel);
oTable.bindRows("/modelData",tableRowFactory); // does not work
oTable.bindAggregation("rows", "/modelData", tableRowFactory); //doesn't work either
The browser does not show any errors and the table stays empty. I think the function does not even get called but I could not manage to fix it.
Maybe my entire approach is wrong - I don't really understand sapui5's binding and context thingy.
I hope that you can help me with this.
Edit:
I found a kinda hacky solution for this:
var model = oTable.getModel();
var rows = oTable.getRows();
var indicesOfRows = [];
$.each(rows, function (index, row){
indicesOfRows.push(oTable.indexOfRow(row));
});
$.each(rows, function(index, row){
var rowIndex = indicesOfRows[index];
var exists = model.getProperty("existsLocal", oTable.getContextByIndex(rowIndex));
var cells = row.getCells();
if(exists){
$.each(cells, function(index, cell){
if(cell instanceof sap.ui.commons.CheckBox){
row.$().toggleClass("existsLocal", true);
cell.setEnabled(false);
}
})
}
})
Instead you could bind to column with template. You have only rows binding and table does not know the columns.
BTW, You can define "enable" property of the checkbox with formatters. You need factory only for addStyleClass when necessary
So something like that: http://jsbin.com/poyetoqa/1/edit
See my edited solution in the original question. If you have a better working solution feel free to answer. Meanwhile I'll mark the question as answered.
I have an editable Kendo Grid that may have a column with a checkbox to change a boolean value. I have used this solution proposed by OnaBai that is working perfectly!
The only problem is that the checkbox value change is too slow. When user clicks it, it takes about 1 second to change. I realize that the dataItem.set() method is responsible by this delay.
My grid has a considerable amount of data. About 30-40 columns and 300+ lines. It is defined as follows:
$("#mainGrid").kendoGrid({
dataSource: dataSource,
pageable: false,
sortable: true,
scrollable: true,
editable: true,
autoBind: false,
columnMenu: true, // Cria o menu de exibição de colunas
height: getGridHeight(),
toolbar: [/* hide for brevity */],
columns: [/* hide for brevity */],
dataBound: function() { /* hide for brevity. */},
edit: function() { /* hide for brevity. */}
});
Another detail is that, when dataItem.set() is called, it calls dataBound() event but that is not causing the delay. Grid's edit() method is not being called on this process. I don't know if worths to post dataSource code.
I would suggest using the approach from this code library article when it comes to use checkboxes. It does not use the set methods of the model and still works the same way. Even with 2000 records on a single page CheckAll will work flawlessly.
I have found an alternative way for doing what OnaBai proposed and it's working better.
// This is the grid
var grid = $("#mainGrid").data("kendoGrid");
// .flag is a class that is used on the checkboxes
grid.tbody.on("change", ".flag", function (e)
{
// Get the record uid
var uid = grid.dataItem($(e.target).closest("tr")).uid;
// Find the current cell
var td = $(e.target).parent().parent();
// This opens the cell to edit(edit mode)
grid.editCell(td);
// This ones changes the value of the Kendo's checkbox, that is quickly shown,
// changed and then hidden again. This marks the cell as 'dirty' too.
$(td.find("input")[0]).prop("checked", $(e.target).is(":checked") ? "checked" : null).trigger("change").trigger("blur");
}
Should try something like this:
I'll set the column with the Edit button to look like this:
columns.Command(command => {command.Edit().HtmlAttributes(new { id = "btnEdit_" + "${Id}" }); }).Width(100).Hidden(true);
And have it where clicking into the first column (I have an image with a hyperlink) uses an onclick function to programmatically click the Edit button, click the checkbox, then click the Update button. Probably more "old school", but I like knowing it is following the order I would be doing if I were updating it, myself.
I pass in the object ("this"), so I can get the row and checkbox when it appears, the new status as 0 or 1 (I have some code that uses it, not really necessary for this demo, though, so I'm leaving that part out of my function for simplicity), and the ID of that item:
columns.Bound(p => p.IsActive).Title("Active").Width(100).ClientTemplate("# if (IsActive == true ) {# <a href=javascript:void(0) id=btnActive_${Id} onclick=changeCheckbox(this, '0', ${Id}) class='k-button k-button-icontext k-grid-update'><img style='border:1px solid black' id=imgActive src=../../Images/active_1.png /></a> #} else {# <a href=javascript:void(0) id=btnActive_${Id} onclick=changeCheckbox(this, '1', ${Id}) class='k-button k-button-icontext k-grid-update'><img style='border:1px solid black' id=imgActive src=../../Images/active_0.png /></a> #}#");
function changeCheckbox(obj, status, id) {
var parentTr = obj.parentNode.parentNode;
$('[id="btnEdit_' + id + '"]').click();
parentTr.childNodes[5].childNodes[0].setAttribute("id", "btnUpdate_" + id); // my Update button is in the 6th column over
parentTr.childNodes[0].childNodes[0].setAttribute("id", "chkbox_" + id);
$('[id=chkbox_' + id + ']').click().trigger("change");
$('[id=chkbox_' + id + ']').blur();
var btnUpdate = $('[id="btnUpdate_' + id + '"]');
$('[id="btnUpdate_' + id + '"]').click();
}
Code above assumes, of course, the checkbox is in the first column. Otherwise, adjust the first childNodes[0] on that chkbox setAttribute line to the column it sits in, minus one because it starts counting from zero.
I did a solution much like #DontVoteMeDown. But I have a nested grid (master / detail) so I get the parent grid from the event parameter. Also I just trigger a click-event on the checkbox.
$("#grid .k-grid-content").on("change", "input.chkbx", function (e) {
// Get the parent grid of the checkbox. This can either be the master grid or the detail grid.
var parentGrid = $(e.target).closest('div[data-role="grid"]').data("kendoGrid");
// Get the clicked cell.
var td = $(e.target).closest("td");
// Enter the cell's edit mode.
parentGrid.editCell(td);
// Find the checkbox in the cell (which now is in "edit-mode").
var checkbox = td.children("input[type=checkbox]");
// Trigger a click (which will toggle check/uncheck).
checkbox.trigger("click");
});
I want to make a simple table that contains a custom button in a row. When the button is pushed, I want to pop up an 'alert' box. I have read some posts on this, for example:
this post
and
this other post, and I don't understand why my code is not working. The buttons are drawn, but pushing them has no effect.
I have three attempts described here.
Version 1. The button click never fires:
$(document).ready(function(){
jQuery("#simpletable").jqGrid({
datatype: "local",
colNames:['A','B','Status'],
colModel:[
{name:'A',index:'A'},
{name:'B',index:'B'},
{name:'status',index:status}
],
data:[
{'A':2,'B':100,'status':"<button onclick=\"jQuery('#simpletable').saveRow('1', function(){alert('you are in')});\" >in</button>"},
{'A':1,'B':200,'status':"<button onclick=\"jQuery('#simpletable').saveRow('2', function(){alert('you are in')});\" >in</button>"},
],
caption: "Demo of Custom Clickable Button in Row",
viewrecords:true,
editurl:'clientArray',
});
});
Html Code:
<table id="simpletable"></table>
EDIT 8/2/12 -- I've learned some things since my original post and here I describe two more attempts.
Version 2: I use onCellSelect. This works, but it would not allow me to put more than one button in a cell. Additionally, I made the code nicer by using the format option suggested by one of the comments to this post.
function status_button_maker_v2(cellvalue, options, rowObject){
return "<button class=\"ver2_statusbutton\">"+cellvalue+"</button>"
};
jQuery("#simpletablev2").jqGrid({
datatype: "local",
colNames:['A','B','Status'],
colModel:[
{name:'A',index:'A'},
{name:'B',index:'B'},
{name:'status',index:status,editable:true,formatter:status_button_maker_v2}
],
data:[
{'A':2,'B':100,'status':"In"},
{'A':1,'B':200,'status':"Out"}
],
onCellSelect:function(rowid,icol,cellcontent,e){
if (icol==2){
alert('My value in column A is: '+$("#simpletablev2").getRowData(rowid)['A']);
}else{
return true;
}
},
caption: "Demo of Custom Clickable Button in Row, ver 2",
viewrecords:true,
}); //end simpletablev2
Markup:
<style>.ver2_statusbutton { color:blue;} </style>
<h3>simple table, ver 2:</h3>
<table id="simpletablev2"></table>
Version 3: I tried to use the solution to w4ik's post, using ".on" instead of deprecated ".live". This causes the button click to fire, but I don't know how to retrieve the rowid. w4ik also struggled with this, and he posted that he worked it out, but not how he did it. I can get the last row selected, but this will always refer to the previous row selected because the button is taking priority.
I would prefer this solution if I could get it to work.
jQuery("#simpletablev3").jqGrid({
datatype: "local",
colNames:['A','B','Status'],
colModel:[
{name:'A',index:'A'},
{name:'B',index:'B'},
{name:'status',index:status,editable:true,formatter:status_button_maker_v3}
],
data:[
{'A':2,'B':100,'status':"In"},
{'A':1,'B':200,'status':"Out"}
],
caption: "Demo of Custom Clickable Button in Row, ver 3",
viewrecords:true,
onSelectRow: function(){},
gridComplete: function(){}
}); //end simpletablev3
$(".ver3_statusbutton").on(
{
click: function(){
//how to get the row id? the following does not work
//var rowid = $("#simpletablev3").attr('rowid');
//
//it also does not work to get the selected row
// this is always one click behind:
//$("#simpletablev3").trigger("reloadGrid");
rowid = $("#simpletablev3").getGridParam('selrow');
alert("button pushed! rowid = "+rowid);
}
});
Markup:
<style>.ver3_statusbutton { color:red;} </style>
<h3>simple table, ver 3:</h3>
<table id="simpletablev3"></table>
In summary, I'm struggling with the issue of getting my button to be pushed at the right time. In version 1, the row gets selected and the button never gets pushed. Version 2 does not use the "button" at all -- It just handles the cell click. Verion 3 gets the button click before the row select (wrong order).
Any help would be appreciated!
You can use action formatter here with each row and make edit and delete button as false in formatOptions like this:
formatoptions: {editbutton:false,delbutton:false}}
And follow these two demos:
http://www.ok-soft-gmbh.com/jqGrid/Admin3.htm
http://ok-soft-gmbh.com/jqGrid/TestSamle/Admin1.htm
And on click event of these custom buttons show your alert:
EDIT
var getColumnIndexByName = function (grid, columnName) {
var cm = grid.jqGrid('getGridParam', 'colModel'), i, l = cm.length;
for (i = 0; i < l; i++) {
if (cm[i].name === columnName) {
return i; // return the index
}
}
return -1;
},
function () {
var iCol = getColumnIndexByName(grid, 'act');
$(this).find(">tbody>tr.jqgrow>td:nth-child(" + (iCol + 1) + ")")
.each(function() {
$("<div>", {
title: "Custom",
mouseover: function() {
$(this).addClass('ui-state-hover');
},
mouseout: function() {
$(this).removeClass('ui-state-hover');
},
click: function(e) {
alert("'Custom' button is clicked in the rowis="+
$(e.target).closest("tr.jqgrow").attr("id") +" !");
}
}
).css({"margin-right": "5px", float: "left", cursor: "pointer"})
.addClass("ui-pg-div ui-inline-custom")
.append('<span class="ui-icon ui-icon-document"></span>')
.prependTo($(this).children("div"));
});
}
If you check this code, I'm trying to find out index value by giving column name as 'act', you can get index on any other column by giving a different column name.
var iCol = getColumnIndexByName(grid, 'Demo'); and the rest of the code will be same for you. //demo is the column name where u want to add custom button
and write your click event for this button.
Let me know if this works for you or not.