jqgrid: Change editable cell to not editable according to the cell value in form editing - jqgrid

My problem is that i want to change the cell being editable or not in the edit form according to the content of the cell of the row that is selected to be edited.
I used Oleg's example to this link: JQGrid: Dynamically set a cell to uneditable based on content to figure out how to change the cell from editable to not editable but i cannot get the cell value in order to compare it and decide if i want to change the edit option of the cell.
UPDATED CODE:
var Setcelluneditable=function(form) {
return function (form) {
var id = jQuery(list).getGridParam('selrow');
var ret = jQuery(list).jqGrid('getRowData',id);
alert("Arrived="+ret.Arrived);
if (ret.Arrived=='Yes')
{alert("hello"+id);
jQuery(list).setCell(id,'Arrived','',{color:'red'}, editable:'0'});}
}
};
jQuery(list).jqGrid('navGrid',pager,{edit:true,add:true,del:true,search:false,view:true, reload:true},
{
width:colwidth,
height:"auto",
reloadAfterSubmit:true,
closeAfterEdit: true,
recreateForm: true,
ajaxEditOptions: {cache: false},
beforeInitData : Setcelluneditable("#editmod")
},
{
width:colwidth,
height:"auto",
reloadAfterSubmit:true,
closeAfterAdd: true,
recreateForm: true,
drag: false
},
{},
{},
{},
{});
This does not seem to work because i change the Grid that has already been constructed.

I think i found out the way to do that but it does not seem to me the best one can have:
onSelectRow: function(id){
var ret = jQuery(list).jqGrid('getRowData',id);
if (ret.Arrived=='Yes')
{
jQuery(list).setColProp('Arrived',{editable:false});}
else { jQuery(list).setColProp('Arrived',{editable:true});}}
I change the ColProp every time one Selects a Row.

selRowId = $(list).jqGrid ('getGridParam', 'selrow');
var cm = $(list).jqGrid('getGridParam', 'colModel');
for(x=0; x<cm.length; x++){
if(cm[x].name == 'ID'){
$('#' + selRowId + '_' + cm[x].name).attr('disabled', true);
}
}
code in onSelectRow event

Related

Which event gets fired when delete row occurs?

Grid contains after save row event "jqGridInlineAfterSaveRow" which works if you edit or add row.
//--Bind events...
console.log('Bind events...');
$("#jqGrid").bind("jqGridInlineAfterSaveRow",function (e, rowid, jqXhrOrBool, postData, options) {
console.log('EVENT:jqGridInlineAfterSaveRow');
var item = $(this).jqGrid('getLocalRow', rowid);
console.log(item);
console.log('BEFORE:');
saveObject(item);
console.log('AFTER:');
});
What is name of the event for delete row? i need to bind my JS function for delete row.
UPDATE 1
I am trying following option now, but no luck...
}).jqGrid("navGrid", "#jqGridPager", {edit: false, add: false, del: false, refresh: false, view: false,search: false,
delfunc: function (rowids) {
console.log(rowids);
}
})
UPDATE 2
I think issue is with delete buttons at row level not at footer
see the screenshot [enter image description here][1]
data:rdata,
colModel: [
{
label: "",
name: "",
width: 70,
formatter: "actions",
formatoptions: {
keys: true,
editOptions: {},
addOptions: {},
delOptions: { delfunc : function (id){
console.log(">>>>>>>>>>>>>>>>1");
}}
}
},
UPDATE 3
Based on Oleg's input, i have changed the code as following:
$("#jqGrid").bind("jqGridAfterDelRow",function (e, rowid, jqXhrOrBool, postData, options) {
console.log('EVENT:jqGridAfterDelRow');
console.log(rowid);
var item = $(this).jqGrid('delRowData ', rowid);
console.log(item);
console.log('BEFORE:');
console.log('AFTER:');
});
But now, i am not getting deleted row object??? Actually, i need to get the some of the fields from deleted row e.g. ID. and above binding function will in turn call server side ajax function.
UPDATE 4
Thanks to Oleg for supporting beyond... Here is the code i have mashup from one of the answers from him.
colModel: [
{
label: "",
name: "",
width: 70,
formatter: "actions",
formatoptions: {
keys: true,
editbutton : true,
delbutton : true,
editOptions: {},
addOptions: {},
delOptions: {
onclickSubmit: function(options, rowid) {
console.log("delOptions::onclickSubmit");
var grid_id = $.jgrid.jqID(grid[0].id);
var grid_p = grid[0].p;
var newPage = grid[0].p.page;
var rowdata = grid.getLocalRow(rowid);
// DELETE GRID LOCAL ROW
grid.delRowData(rowid);
$.jgrid.hideModal("#delmod"+grid_id,
{gb:"#gbox_"+grid_id,jqm:options.jqModal,onClose:options.onClose});
if (grid_p.lastpage > 1) {// on the multipage grid reload the grid
if (grid_p.reccount === 0 && newPage === grid_p.lastpage) {
// if after deliting there are no rows on the current page
// which is the last page of the grid
newPage--; // go to the previous page
}
// reload grid to make the row from the next page visable.
grid.trigger("reloadGrid", [{page:newPage}]);
}
return true;
},
processing:true
}
}
},
You can use "jqGridAddEditAfterComplete" event, which will be triggered after deleting of rows by delGridRow, or you can use "jqGridAfterDelRow" alternatively, because delGridRow calls delRowData internally and jqGridAfterDelRow will be triggered by delRowData.
For deleting row use below code snippet:
$('#gridId').jqGrid('delRowData',rowid);
$("#yourGridTable").jqGrid(
"navGrid",
"#yourGridTablePager",
{
del: true
},
{},
{},
{
// This event is fired when delete button is pressed in pager
//
beforeSubmit:function(){
console.log("After delete button of pager is clicked");
}
}
);

How to get row index and cell index of row click kendo grid

I have added onchange event for kendo-ui grid.
In that I am trying to get the ID value for that particular row. I have added an image column as first column in the grid. What I want is when the image is clicked, I want to open a image url.
So, basically what I want is that when I click the row, I want to get the clicked row index and also I want to get the clicked cell Index in that row.
So based on the row clicked and if it is not the first cell clicked, I want to display alert. If I the first cell is clicked I want to open image.
How can I get this index.
I have set selectable : row in the kendo-ui grid
Please help me on this.
Please try with below code snippet.
function onDataBound(e) {
var grid = $("#Grid").data("kendoGrid");
$(grid.tbody).on("click", "td", function (e) {
var row = $(this).closest("tr");
var rowIdx = $("tr", grid.tbody).index(row);
var colIdx = $("td", row).index(this);
alert(rowIdx + '-' + colIdx);
});
}
$(document).ready(function () {
$("#Grid").kendoGrid({
dataSource: {
type: "odata",
transport: {
read: "http://demos.kendoui.com/service/Northwind.svc/Orders",
dataType: "jsonp"
},
schema: {
model: {
fields: {
OrderID: { type: "number" },
Freight: { type: "number" },
ShipName: { type: "string" },
OrderDate: { type: "date" },
ShipCity: { type: "string" }
}
}
},
pageSize: 10,
serverPaging: true,
serverFiltering: true,
serverSorting: true
},
dataBound: onDataBound,
filterable: true,
sortable: true,
pageable: true,
columns: [{
field: "OrderID",
filterable: false
},
"Freight",
{
field: "OrderDate",
title: "Order Date",
width: 120,
format: "{0:MM/dd/yyyy}"
}, {
field: "ShipName",
title: "Ship Name",
width: 260
}, {
field: "ShipCity",
title: "Ship City",
width: 150
}
]
});
});
<div id="Grid"></div>
If all you need is knowing the row and column index in the table you can do:
$(grid.tbody).on("click", "td", function(e) {
var row = $(this).closest("tr");
var rowIdx = $("tr", grid.tbody).index(row);
var colIdx = $("td", row).index(this);
console.log("row:", rowIdx, "cell:", colIdx);
});
Where I set a click handler for clicking in the cells of the grid.
Then I find to which row (<tr>) that cell belongs to using jQuery closest.
Next use jQuery index for finding the index of that row in the table.
Do the same for finding the cell index inside the row.
But maybe there are simpler ways as detecting if the user clicked on an image, or set some CSS class in the image and then check if the clicked cell has that class,...
EDIT If in addition you want to retrieve the original item inside the click handler. Add
var item = grid.dataItem(row);
From there, you can get id or any other field for validation.
Example here : http://jsfiddle.net/OnaBai/MuDX7/
Kendo has introduced frozen columns since the question has been answered so I think it deserved a little update to deal with that feature.
When you have a frozen column, the grid will create new header / content tables to manage the frozen columns. If you freeze a column, it will move item linked to this column from the regular grid's tbody / thead to the lockedContent / lockedHeader (the opposite is also true).
If you get the index using the accepted answer, you'll get the index of the cell within the tbody (or -1 if the cell is frozen). The real question is what do you want to do with the column index? If you really want an index number, you may have to adjust the value by adding the number of columns in the lockedContent depending on your needs. However, if your final goal is to get the grid's column object, this can be done by using the th element:
var row = cell.closest("tr");
var body;
var header;
if (cell.closest(grid.lockedContent).length) {
body = grid.lockedContent;
header = grid.lockedContent;
} else {
body = grid.tbody;
header = grid.thead;
}
var rowIndex = $("tr", body).index(row);
var columnIndex = $("td", row).index(cell);
var columnField = header.find("th").eq(columnIndex).attr("data-field");
var column;
$.each(grid.columns, function () {
if (this.field === columnField) {
column = this;
return false;
}
});
Disclaimer: just to add a level of complexity, you should also consider that kendo has also introduced a multiple column header feature that may invalidate my code above.
For the cell index, kendo grid has a method cellIndex(cell)
var cell = $("#grid td:eq(1)");
console.log(grid.cellIndex(cell));

jqGrid change dynamically edittype for specific row

Following to this post where I found some way to do that I would want to get, I meet some trouble with it.
Here is my code :
var myDlg = $("#dlgpers"),lastsel;
myDlg.jqGrid({
url:'pers.php?id='+dataRow.id,
mtype:'GET',
datatype: "json",
ajaxGridOptions: { cache: false },
height:250,
cmTemplate: {sortable:false},
gridview: true,
cellEdit:true,
scroll:false,
colNames:['Id','Label','Information','Type','Data'],
colModel:[
{name:'id',index:'id',hidden:true,key:true},
{name:'label',index:'label',align:'right',width:100,editable:false,
cellattr: function (rowId, val, rawObject, cm, rdata) {
return ' style="font-weight:bold;margin-right:5px;border-left:0;border-top:0;" class="ui-state-active"' ;
}
},
{name:'info',index:'info',width:200,editable:true,edittype:'text'},
{name:'type',index:'type',width:30,hidden:true},
{name:'data',index:'data',width:30,hidden:true}
],
loadComplete: function () {
var rowIds = myDlg.jqGrid('getDataIDs');
$.each(rowIds, function (i, row) {
var rowData = myDlg.jqGrid('getRowData',row);
if (rowData.type == 'select') {
myDlg.jqGrid('restoreRow', row);
var cm = myDlg.jqGrid('getColProp', 'info');
cm.edittype = 'select';
cm.editoptions = { value: rowData.data };
myDlg.jqGrid('editRow', row);
cm.edittype = 'text';
cm.editoptions = null;
cm.editable = true;
}else{
myDlg.jqGrid('restoreRow', row);
var cm = myDlg.jqGrid('getColProp', 'info');
cm.edittype = 'text';
cm.editoptions = null;
cm.editable = true;
myDlg.jqGrid('editRow', row);
cm.edittype = 'text';
cm.editoptions = null;
cm.editable = true;
}
});
}
});
and the result as image :
and the JSON response :
{"page":1,"total":1,"records":1,"rows":[
{"cell":[0,"Nom ","LEBRUN","text",""]},
{"cell":[1,"Pr\u00e9nom ","Jacques","text",""]},
{"cell":[2,"Initiales ","LJ","text",""]},
{"cell":[3,"Fonction ","","text",""]},
{"cell"[4,"Service,"Administratif","select","0:Administratif;1:Commercial;2:Magasin;3:M\u00e9canique;4:Rejointage;5:Soudure;6:Tests"]},
{"cell":[5,"T\u00e9l\u00e9phone ","","text",""]},
{"cell":[6,"Email ","","text",""]},
{"cell":[7,"Statut ","CDI","select","0:CDI;1:CDD;2:App;3:Stg;4:Int"]},
{"cell":[8,"Entr\u00e9 le ","2008-10-06","text",""]},
{"cell":[9,"Sorti le ","0000-00-00","text",""]}]}
Two questions I submit to your knowledge:
As you can see, the second line (Prénom) don't seem editable, but it is.
I don't understand why these inputs are visible, as I would want they appear only if I edit some cell.
Many thanks for all your kind help for resolve (and explain) my wrong way.
JiheL
UPDATED 2013-03-29
I have applied your answer code and that run fine ! Many thanks.
But I have created another form in such a way for another subject, and that cause me some troubles.
Here is the code of this new form :
var showAbs=function(){
$('#EditDialog').empty();
var $table=$('<table></table>')
.attr('id','dlgcong')
.appendTo($('#EditDialog'));
var myCong = $("#dlgcong");
myCong.jqGrid({
url:'xpabs.php?id='+id+'&y='+y,
datatype: "json",
height:"auto",
cmTemplate: {sortable:false},
gridview: true,
colNames:['Type absence','Début','Fin','id'],
colModel:[
{name:'abs',index:'abs',width:155,editable:true,edittype:'select',
editoptions:{
dataUrl:"selabs.php",
dataEvents: [
{
type: 'change',
fn: function(e) {
$(this).parent().css('background-color','#'+$(this).find('option:selected').attr('colr'));
if($(this).find('option:selected').attr('colr')=='ffffff'){
$(this).parent().parent().find('input').datepicker('disable');
}else{
$(this).parent().parent().find('input').datepicker('enable');
$(this).parent().parent().attr('changed',true);
}
}
}
]
},
cellattr: function (rowId, val, rawObject, cm, rdata) {
return ' style="background-color:#'+rawObject[4]+';color:white;"';
}
},
{name:'debut',index:'debut',align:'center',width:70,editable:true},
{name:'fin',index:'fin',align:'center',width:70,editable:true},
{name:'id',index:'id',hidden:true}
],
jsonReader: {
cell: "",
root: function (obj) {
return obj;
}
},
loadComplete: function (data) {
var $self = $(this),
cm = $self.jqGrid("getColProp", "debut"),
idPrefix = $self.jqGrid("getGridParam", "idPrefix"),
l = data.length,
i,
item;
for (i = 0; i < l; i++) {
item = data[i];
cm.editoptions = {
dataInit: function(element) {
$(element).datepicker({
setDate:item[1],
minDate:'01/01/'+y,
maxDate:'31/12/'+y,
onSelect: function( selectedDate,inst ) {
$(element).val(selectedDate );
$(element).parent().parent().attr('changed',true);
}
})
}
}
}
var cm = $self.jqGrid("getColProp", "fin");
for (i = 0; i < l; i++) {
item = data[i];
cm.editoptions = {
dataInit: function(element) {
$(element).datepicker({
setDate:item[2],
minDate:'01/01/'+y,
maxDate:'31/12/'+y,
onSelect: function( selectedDate,inst ) {
$(element).val(selectedDate );
$(element).parent().parent().attr('changed',true);
}
})
}
}
$self.jqGrid("editRow", idPrefix + item[3]);
}
myCong.find('select').each(function(){
$(this).css({
backgroundColor:'transparent',
color:'white',
border:0,
width:155
});
});
},
idPrefix: "cong",
rowNum: 10000
});
//********************
// Button ' Valider '
//********************
$('<input />')
.attr({
type:'button',
})
.css({
float:'right',
marginTop:'5px'
})
.click(function(){
var toBeSaved='';
myCong.find('tr[changed=true]').each(function(idx){
if(toBeSaved.length>0){
toBeSaved+='|';
}
toBeSaved+=$(this).find('td:eq(3)').text()+';';
toBeSaved+=$(this).find('select option:selected').val()+';';
toBeSaved+=$(this).find('input:eq(0)').val()+';';
toBeSaved+=$(this).find('input:eq(1)').val();
});
if(toBeSaved.length>0){
$.ajax({
url:'majpabs.php?id='+id+'&data='+toBeSaved,
async:false,
dataType:'json',
success:function(data){
myGrid.trigger('reloadGrid');
$('#newAbs').val(' Nouveau ').attr('disabled',false);
}
});
}
})
.val(' Valider les absences ')
.appendTo($('#EditDialog'));
//*******************
// Button ' Retour '
//*******************
$('<input />')
.attr({
type:'button',
id:'newAbs'
})
.css({
float:'left',
marginTop:'5px'
})
.click(function(){
showPers();
})
.val(' Retour ')
.appendTo($('#EditDialog'));
//********************
// Button ' Nouveau '
//********************
$('<input />')
.attr({
type:'button',
disabled:false
})
.css({
float:'left',
marginTop:'5px',
marginLeft:'7px'
})
.click(function(){
if($(this).val()==' Nouveau '){
var myRow = {abs:"0", debut:'00/00/'+y, fin:'00/00/'+y, id:'0'};
myCong.jqGrid('addRowData','',myRow, 'last');
$(this).val(' Sauver ').attr('disabled',true);
}else{
}
})
.val(' Nouveau ')
.appendTo($('#EditDialog'));
}
and the result as image :
As you can see, the first row does not receive select and datepicker as other rows. Strange !
When I add new row, it does not receive select and datepicker as the first row.
I think I'm wrong in understanding this method.
I'm worry to bother you with these questions, I had a look in wiki without success to find any way to make these points correct. I would like to find some more detailed tutorial which show some cases examples.
Thank you VERY MUCH if you can spend again some time for give me a way to be more efficient with jqGrid.JiheL
UPDATED 2013-04-01
I have applied Oleg's suggestions and that works now. But a trouble remains.
here is the image :
For the first row, select box is OK.
The first input field receive datepicker, but the second (the column called 'fin') not !
All others rows receive well datepickers, but not the last field of first row.
Here is the code :
loadComplete: function (data) {
var $self = $(this),
idPrefix = $self.jqGrid("getGridParam", "idPrefix"),
l = data.length,
i,
item,
cm;
for (i = 0; i < l; i++) {
item = data[i];
cm = $self.jqGrid("getColProp", "debut");
cm.editoptions = {
dataInit: function(element) {
//alert('deb'+i);
$(element).datepicker({
setDate:item[1],
minDate:'01/01/'+y,
maxDate:'31/12/'+y,
onSelect: function( selectedDate,inst ) {
$(element).val(selectedDate );
$(element).parent().parent().attr('changed',true);
}
})
}
};
$self.jqGrid("editRow", idPrefix + item[3]);
//
cm = $self.jqGrid("getColProp", "fin");
cm.editoptions = {
dataInit: function(element) {
//alert('fin'+i);
$(element).datepicker({
setDate:item[2],
minDate:'01/01/'+y,
maxDate:'31/12/'+y,
onSelect: function( selectedDate,inst ) {
$(element).val(selectedDate );
$(element).parent().parent().attr('changed',true);
}
})
}
};
$self.jqGrid("editRow", idPrefix + item[3]);
}
myCong.find('select').each(function(){
$(this).css({
backgroundColor:'transparent',
color:'white',
border:0,
width:155
});
});
},
Another time, I hope you can help me to resolve this trouble and close this request.
Many thanks for all the time you spend to help newbies.
JiheL
I think that many from the problems in your code common. So I tried to answer on you question more detailed.
First of all you posted wrong JSON data. The line
{"cell"[4,"Service,"Administratif","select","0:Administratif;1:Commercial;2:Magasin;3:M\u00e9canique;4:Rejointage;5:Soudure;6:Tests"]},
contains two errors:
no ':' after "cell"
no " after "Service
After the changes the line will be so
{"cell":[4,"Service","Administratif","select","0:Administratif;1:Commercial;2:Magasin;3:M\u00e9canique;4:Rejointage;5:Soudure;6:Tests"]},
and JSON data could be read. The next problem is the usage of numbers together with string in one array. Because the bug in the line of jqGrid code
idr = ccur !== undefined ? ccur[idn] || idr : idr;
ids could not be integer value 0. I posted the bug report about the error. To fix the problem using existing code of jqGrid you should use strings instead of numbers. For example the line
{"cell":[0,"Nom ","LEBRUN","text",""]},
should be changed to
{"cell":["0","Nom ","LEBRUN","text",""]},
Without the changes you will have id duplicates. Both first lines ({"cell":[0,"Nom ","LEBRUN","text",""]} and {"cell":[1,"Pr\u00e9nom ","Jacques","text",""]},) will get the same id equal to 1 instead of 0 and 1. It was the main reason of the problem which you described.
Additionally I would recommend you the following:
remove cellEdit:true option. You use editRow later in the code. It means that you use inline editing instead of cell editing which means cellEdit:true. You can't combine both editing modes in one grid.
replace height:250 option to height:"auto"
remove all index properties from colModel. Remove all properties of colModel with default values (edittype:'text', editable:false)
remove options of jqGrid with default values (mtype:'GET', scroll:false)
all parameters of functions in JavaScript are optional. So if you don't use for example any parameters of cellattr callback you can replace cellattr: function (rowId, val, rawObject, cm, rdata) {...} to cellattr: function () {...}
the callback loadComplete has one parameter data which can provide you all data which returned from the server. So you don't need to use getDataIDs and getRowData. The array data.rows can by directly used.
if you use data parameter of loadComplete callback you can remove unneeded 'type' and 'data' columns from the grid.
if you place information about id after 'Label','Information' then you can use id property of jsonReader and remove hidden id column from the grid too. For example if you move id as the last in the cell array you can use jsonReader: {id: 4} and remove hidden id column from the grid. If you add additionally cell: "" property in jsonReader you can remove "cell": from the input data. If you would use root property of jsonReader defined as function (see the documentation) you can remove some unneeded data from the server response.
For example the server can produce the simplified data
[
["Nom ","LEBRUN","text","","0"],
["Pr\u00e9nom ","Jacques","text","","1"],
["Initiales ","LJ","text","","2"],
["Fonction ","","text","","3"],
["Service","Administratif","select","0:Administratif;1:Commercial;2:Magasin;3:M\u00e9canique;4:Rejointage;5:Soudure;6:Tests","4"],
["T\u00e9l\u00e9phone ","","text","","5"],
["Email ","","text","","6"],
["Statut ","CDI","select","0:CDI;1:CDD;2:App;3:Stg;4:Int","7"],
["Entr\u00e9 le ","2008-10-06","text","","8"],
["Sorti le ","0000-00-00","text","","9"]
]
The corresponding jqGrid could be
$("#dlgpers").jqGrid({
url: "pers.php?id=" + dataRow.id,
datatype: "json",
height: "auto",
cmTemplate: {sortable: false},
gridview: true,
colNames: ["Label", "Information"],
colModel: [
{name: "label", align: "right", width: 100,
cellattr: function () {
return ' style="font-weight:bold;margin-right:5px;border-left:0;border-top:0;" class="ui-state-active"';
}},
{name: "info", width: 200, editable: true}
],
jsonReader: {id: 4, cell: "", root: function (obj) { return obj; } },
loadComplete: function (data) {
var $self = $(this),
cm = $self.jqGrid("getColProp", "info"),
idPrefix = $self.jqGrid("getGridParam", "idPrefix"),
l = data.length,
i,
item;
for (i = 0; i < l; i++) {
item = data[i];
cm.edittype = item[2] === "select" ? "select" : "text";
cm.editoptions = { value: item[3] };
$self.jqGrid("editRow", idPrefix + item[4]);
}
},
idPrefix: "dlg",
rowNum: 10000 // to have no paging
});
See the demo:

Refers to: jqgrid: how to set toolbar options based on column value in row selected

my question refers to http://goo.gl/f0Boc
The code works fine for me, but now I want to enable/disable the "Edit-Button" when the value in a cell is "Yes" or "No".
In this example is written:
// you can use getCell or getRowData to examine the contain of
// the selected row to decide whether the row is editable or not
I need an explanation how I could change the code so that the code runs with jqGrid('getCell',rowid,'cellContent')?
What I need is if cellContent is "Yes" then disable "Edit-Button".
Thanks in advance for your efforts,
best regards
Stephan
<script type="text/javascript">
$(function(){
$("#list").jqGrid({
url:'example.php',
datatype: 'xml',
mtype: 'GET',
colNames:['User ID','Name', 'Firstname','CDS-ID','E-mail','Password', 'Registration
Date','Account Activated', 'Account Activation Date', 'Role'],
colModel :[
{name:'idUser_registration', index:'idUser_registration', width:55,
editable:true, editoptions{readonly:true},search:true},
...
{name:'account_activated', index:'account_activated', width:150, align:'right',
edittype:'checkbox',editoptions: { value:"Yes:No" }, editable:true,
search:true},
... ],
pager: '#pager',
rowNum:10,
rowList:[10,20,30],
sortname: 'idUser_registration',
sortorder: 'asc',
viewrecords: true,
gridview: true,
caption: 'My grid',
editurl: 'example2.php',
beforeSelectRow: function(rowid) {
var selRowId = $(this).getGridParam('selrow'),
celValue = $(this).getCell('getCell', selRowId, 'list_account_activated'),
tr = $("#"+rowid);
// you can use getCell or getRowData to examine the contain of
// the selected row to decide whether the row is editable or not
if (selRowId !== rowid && !tr.hasClass('not-editable-row')) {
// eneble the "Edit" button in the navigator
$("#edit_" + this.id).removeClass('ui-state-disabled');
$("#del_" + this.id).removeClass('ui-state-disabled');
}
else {
// unselect previous selected row
// disable the "Edit" and "Del" button in the navigator
$("#edit_" + this.id).addClass('ui-state-disabled');
$("#del_" + this.id).addClass('ui-state-disabled');
}
return true; // allow selection or unselection
},
loadComplete: function() {
// just one example how to mark some rows as non-editable is to add
// some class like 'not-editable-row' which we test in beforeSelectRow
$("tr.jqgrow:even",this).addClass('not-editable-row');
}
}).jqGrid('navGrid','#pager',
{}, //options
{closeAfterEdit:true,mtype:'GET',editCaption: "Activate
Account",height:400,reloadAfterSubmit:true },
{reloadAfterSubmit:false}, // del options
{} // search options
);
$("#edit_").click(function() {
var gr = jQuery("#list").jqGrid('getGridParam','selrow');
if( gr != null ) jQuery("#list").jqGrid('editGridRow',gr,{});
});
$("#del_").click(function(){
var gr = jQuery("#list").jqGrid('getGridParam','selrow');
if( gr != null ) jQuery("#list").jqGrid('delGridRow',gr,{mtype:'GET',reloadAfterSubmit:true});
});
});
</script>
I modified the referenced demo for you. The main part of the code is the following
onSelectRow: function (rowid) {
var thisId = $.jgrid.jqID(this.id),
isCompleted = $(this).jqGrid("getCell", rowid, "isCompleted");
// you can use getCell or getRowData to examine the contain of
// the selected row to decide whether the row is editable or not
if (isCompleted !== "Yes") {
// eneble the "Edit" button in the navigator
$("#edit_" + thisId).removeClass('ui-state-disabled');
$("#del_" + thisId).removeClass('ui-state-disabled');
} else {
// unselect previous selected row
// disable the "Edit" and "Del" button in the navigator
$("#edit_" + thisId).addClass('ui-state-disabled');
$("#del_" + thisId).addClass('ui-state-disabled');
}
}
You can see new demo here.

jqgrid Subgrid as a Grid: Edit, Add, Search Icons not appearing in Subgrid

This is the code for my Grid. But for some reason the edit, add, and search icons are not displaying in subgrid:
$(document).ready(function(){
var gridwidth = $('.tableContainer').width();
gridwidth = gridwidth-40;
var myGrid = jQuery("#list");
editSettings = {
recreateForm:true,
reloadAfterSubmit:false,
closeOnEscape:true,
closeAfterEdit:true,
width:"1250"
},
addSettings = {
recreateForm:true,
reloadAfterSubmit:false,
closeOnEscape:true,
closeAfterAdd:true
};
myGrid.jqGrid(
{
url:'projects.cfc?method=getProjects&returnformat=json&_cf_nodebug=true', //CFC that will return the projects
datatype: 'json', //We specify that the datatype we will be using will be JSON
complete: function(jsondata, stat) {
if (stat == "success") {
myGrid = jQuery("#list")[0];
myGrid.addJSONData(JSON.parse(jsondata.responseText).d);
} else {
alert('Error processing JSON');
}
},
colNames:[ .....],
colModel :[{ ...}], //it the operators available during search
pager: $('#pager'), //The div we have specified, tells jqGrid where to put the pager
rowNum: 150, //Number of records we want to show per page
rowList:[20,30,40,50,75,150], //Row List, to allow Initiative to select how many rows they want to see per page
sortorder: "asc", //Default sort order
sortname: "PROJECTS.PROJECTID", //Default sort column
viewrecords: true, //Shows the nice message on the pager
imgpath: '/images', //Image path for prev/next etc images
caption: 'Initiatives', //Grid Name
recordtext: "Record {0} - {1} of {2}",//Pager information to show
rownumbers: false,//Do not show row numbers
sortable: true,
width:'auto',
height:'auto', //I like auto, so there is no blank space between. Using a fixed height can mean either a scrollbar or a blank space before the pager
mtype:'POST',
toolbar:[true,"bottom"], //Shows the toolbar at the top. We will use it to display Initiative feedback
subGrid: true,
subGridRowExpanded: function(subgrid_id, row_id) {
// we pass two parameters
// subgrid_id is a id of the div tag created within a table
// the row_id is the id of the row
// If we want to pass additional parameters to the url we can use
// the method getRowData(row_id) - which returns associative array in type name-value
// here we can easy construct the following
var subgrid_table_id, pager_id;
subgrid_table_id = subgrid_id+"_t";
pager_id = "p_" + subgrid_table_id;
jQuery("#"+subgrid_id).html("<table id='"+subgrid_table_id+"' cellpadding='0' cellspacing='0' class='scroll'></table><div id=’" + pager_id + "’ class=’scroll’></div>");
jQuery("#"+subgrid_table_id).jqGrid({
url:"projects.cfc?method=getProjectMilestones&projectid="+row_id,
datatype: "json",
colNames:['SEQ','ID','MILESTONE','TREND','DUE DATE','STATUS','OWNERS','%','COMMENTS'], //Column Names
//The Column Model to define the data. Note you can make columns non sortable, specify width, alignment, etc.
colModel :[
{name:'SEQUENCENUM',index:'SEQUENCENUM',hidden:true},
{name:'PROJECTID',index:'PROJECTID', editable:false},
{name:'MILESTONE',index:'MILESTONE', width:150, sorttype:"text",align:"center",
editable:true,edittype:"text",
editrules:{required:true}},
{name:'TREND',index:'TREND', width:100, align:"center",sorttype:"text",
editable:true,edittype:"select",editoptions:{value:"Green:Green;Yellow:Yellow;Red:Red"},
editrules:{required:true}},
{name:'DUE_DATE',index:'DUE_DATE', width:150, editable:true,editoptions:{size:12,dataInit: function(el) {
$(el).datepicker({ dateFormat: 'mm-dd-yy'} );
},
defaultValue: function() {
var currentTime = new Date();
var month = parseInt(currentTime.getMonth() + 1);
month = month <= 9 ? "0" + month : month;
var day = currentTime.getDate();
day = day <= 9 ? "0" + day : day;
var year = currentTime.getFullYear();
return month + "-" + day + "-" + year ;
}
},align:"center",
editrules:{required:true}},
{name:'MILESTONE_STATUS',index:'MILESTONE_STATUS',
editable:true,edittype:"select",editoptions:{value:"In Progress:In Progress;Complete:Complete"},
editrules:{required:true}},
{name:'ASSIGNMENT',index:'ASSIGNMENT', width:125,align:"center",sorttype:"text",
editable:true,edittype:"text",
editrules:{required:true}},
{name:'PERCENT_COMP',index:'PERCENT_COMP', width:50, sorttype:"int",align:"center",
editable:true,edittype:"text",editrules:{number:true}},
{name:'COMMENTS',index:'COMMENTS', width:200,
editable:true,edittype:"textarea",editoptions:{rows:3, cols:30},
editrules:{required:true}}
],//searchoptions parameter is used to limit the operators available during search,
rowNum: 20, //Number of records we want to show per page
rowList:[20,30,40,50], //Row List, to allow Initiative to select how many rows they want to see per page
sortorder: "asc", //Default sort order
sortname: "SEQUENCENUM", //Default sort column
viewrecords: true, //Shows the nice message on the pager
imgpath: 'images/', //Image path for prev/next etc images
caption: 'Milestones', //Grid Name
recordtext: "Record {0} - {1} of {2}",//Pager information to show
rownumbers: false,//Do not show row numbers
sortable: true,
width:'auto',
height:'auto', //I like auto, so there is no blank space between. Using a fixed height can mean either a scrollbar or a blank space before the pager
mtype:'POST',
toolbar:[true,"bottom"], //Shows the toolbar at the top. We will use it to display Initiative feedback
shrinkToFit: true,
//The JSON reader. This defines what the JSON data returned from the CFC should look like
jsonReader: {
root: "ROWS", //our data
page: "PAGE", //current page
total: "TOTAL", //total pages
records:"RECORDS", //total records
userdata:"USERDATA",
cell: "", //Not Used
id: "0", //Will default to first column
subGrid: {
root : "ROWS",
repeatitems: true,
cell: "" //Not Used
}
},
editurl:'projects.cfc?method=addeditMilestone&projectid='+row_id, //The Add/Edit function call
pager:('#' + pager_id)
}).navGrid('#' + pager_id, {
search:false,//title set for hover over display
edit:true,edittitle:"Edit Milestone",width:200,
add:true,addtitle:"Add Milestone",width:200,
del:true,deltitle:"Delete Milestone"
},
// Edit Options. save key parameter will keybind the Enter key to submit.
{editCaption:"Edit Milestone",edittext:"Edit",closeOnEscape:true,closeAfterEdit:true,savekey: [true,13],errorTextFormat:commonError,width:"500"
,reloadAfterSubmit:true,bottominfo:"Fields marked with (*) are required",top:"60",left:"5",right:"5"},
{addCaption:"Add Milestone",closeOnEscape:true,closeAfterAdd:true,savekey: [true,13],errorTextFormat:commonError,width:"500"
,reloadAfterSubmit:true,bottominfo:"Fields marked with (*) are required",top:"60",left:"5",right:"5"},
//Add Options
{url:"projects.cfc?method=delMilestone",caption:"Delete Milestone",closeOnEscape:true,errorTextFormat:commonError,top:"60",left:"70",
reloadAfterSubmit:true} //Delete Options
)
},
shrinkToFit: true,
//The JSON reader. This defines what the JSON data returned from the CFC should look like
jsonReader: {
root: "ROWS", //our data
page: "PAGE", //current page
total: "TOTAL", //total pages
records:"RECORDS", //total records
userdata:"USERDATA",
cell: "", //Not Used
id: "0" //Will default to first
},
loadComplete: function() {
$('#cb').prev().remove();
if($("#list").getGridParam("RECORDS")==0){
$('#noResults').dialog("open");
} else {
var page = $('#list').getGridParam("PAGE");
var records = $('#list').getGridParam("RECORDS");
var recordsPP = $('#list').getGridParam("rowNum");
var x = records/recordsPP;
var returnArray = [];
if(x < page) {
iterLimit = records%recordsPP;
} else {
iterLimit = recordsPP;
}
for(var i=1; i<=iterLimit; i++) {
$('#'+i).children('td:first').next().addClass('link').css("cursor","pointer").css("color","blue").css("text-decoration","underline");
var emitid = $('#'+i).children ('td:first').next().text();
//window.alert(emitid);
$('#'+i).children('td:first').next().click(function() {
emitid = $(this).text();
//window.alert(emitid + ":" + page + ":" + records + ":" + recordsPP + ":" + x);
var link = 'viewInitiative.cfm?projectid='+emitid
window.open(link,'_blank');
});
//returnArray = orderList.find(ord);
var truefalse = typeof returnArray;
if(truefalse != 'boolean') {
$('#list').setSelection(i);
}
}
}
},
loadError:function(xhr, st, err) {
alert('loaderror on quote request grid - ' + st)
},
editurl:"projects.cfc?method=addeditProject", //The Add/Edit function call
ondblClickRow: function(rowid, ri, ci) {
var p = myGrid[0].p;
if (p.selrow !== rowid) {
// prevent the row from be unselected on double-click
// the implementation is for "multiselect:false" which we use,
// but one can easy modify the code for "multiselect:true"
myGrid.jqGrid('setSelection', rowid);
}
myGrid.jqGrid('editGridRow', rowid, editSettings);
}
}).navGrid('#pager',
{
search:true,searchtitle:"Search",//title set for hover over display
edit:true,edittitle:"Edit Initiative",width:1000,
add:true,addtitle:"Add Initiative",width:1000,
del:true,deltitle:"Delete Initiative"
},
// Edit Options. save key parameter will keybind the Enter key to submit.
{editCaption:"Edit Initiative",edittext:"Edit",closeOnEscape:true,closeAfterEdit:true,savekey: [true,13],errorTextFormat:commonError,width:"1250"
,reloadAfterSubmit:true,bottominfo:"Fields marked with (*) are required",top:"60",left:"5",right:"5"},
{addCaption:"Add Initiative",closeOnEscape:true,closeAfterAdd:true,savekey: [true,13],errorTextFormat:commonError,width:"1250"
,reloadAfterSubmit:true,bottominfo:"Fields marked with (*) are required",top:"60",left:"5",right:"5"},
//Add Options
{url:"projects.cfc?method=delProject",caption:"Delete Initiative",closeOnEscape:true,errorTextFormat:commonError,top:"60",left:"70",
reloadAfterSubmit:true}, //Delete Options
//Search Options. multipleSearch parameter lets it know we are going to use the new advanced search feature
{errorTextFormat:commonError,Find:"Search",closeOnEscape:true,caption:"Search Initiatives",multipleSearch:true,closeAfterSearch:true}
).navButtonAdd('#pager',{
caption:"Export to Excel",
buttonicon:"images/sizzlejs_32x32.png",
onClickButton: function(){
exportExcel();
},
position:"last"
});
function exportExcel()
{
var mya=new Array();
mya=$("#list").getDataIDs(); // Get All IDs
var data=$("#list").getRowData(mya[0]); // Get First row to get the labels
var colNames=new Array();
var ii=0;
for (var i in data){colNames[ii++]=i;} // capture col names
var html="";
for (var k=0;k<colNames.length;k++)
{
if(colNames[k] == "PROJECTID") {
html=html+"EMIT_ID"+"\t";
} else if (colNames[k] == "PROJECT_TITLE") {
html=html+"INITIATIVE_TITLE"+"\t";
} else if (colNames[k] == "PROJECT_TYPE") {
html=html+"SUB-CATEGORY"+"\t";
} else if (colNames[k] == "PROJECT_TYPEID") {
html=html+"SUB_CAT_ID"+"\t";
} else if (colNames[k] == "SUB_TEAM") {
html=html+"SUB_TEAM_MEMBERS"+"\t";
} else if (colNames[k] == "OVERRIDE") {
html=html+"OVERRIDE%_COMP"+"\t";
} else if (colNames[k] == "EM_EXECUTION_TOP_TEN") {
html=html+"EM_EXECUTION_PAIN_POINT"+"\t";
} else {
html=html+colNames[k]+"\t"; // output each Column as tab delimited
}
}
html=html+"\n";
for(i=0;i<mya.length;i++)
{
data=$("#list").getRowData(mya[i]); // get each row
for(j=0;j<colNames.length;j++)
{
html=html+data[colNames[j]]+"\t"; // output each column as tab delimited
}
html=html+"\n"; // output each row with end of line
}
html=html+"\n"; // end of line at the end
document.forms[0].csvBuffer.value=html;
document.forms[0].method='POST';
document.forms[0].action='http://bfops01.edc.cingular.net/excel/csvExport.php'; // send it to server which will open this contents in excel file
document.forms[0].target='_blank';
document.forms[0].submit();
}
//Function will be called when add/edit encounters an error. The returned message is what will be shown to Initiative
function commonError(data){
return "Error Occured during Operation. Please try again";
}
});
You should verify your code in the http://www.jslint.com/. It has many syntax errors. For example, you forget to declare variables iterLimit and j, you should replace ';' after var myGrid = jQuery("#list") to ',' and many other small problems. I recommend you additionally to use integer values for width parameter in many places of the code like jqGrid use ifself.
You main problem seems to me exist because the <div> for the subgrid will be either not created or has no or wrong id element. The code
jQuery("#"+subgrid_id).html("<table id='"+subgrid_table_id+
"' cellpadding='0' cellspacing='0' class='scroll'></table><div id=’" +
pager_id + "’ class=’scroll’></div>");
contain special character ’ instead of '. It should be replaced to
jQuery("#"+subgrid_id).html("<table id='"+subgrid_table_id+
"'></table><div id='" + pager_id + "'></div>");
You use very very old syntax for HTML elements and use retro parameters like imgpath which are deprecated since version 3.5 of jqGrid.

Resources