Reloading of data in JQgrid on button click is not working - jqgrid

I have successfully loaded data in my grid. I have enabled cell edit and on clicking a cell it will be in edit mode and multiple cells can be edited. The edited data will be stored later on clicking a custom update button. On clicking another custom button a new row will be added to the grid and that also will be saved on clicking the update button previously mentioned.
Now the problem is when I am trying to reset the edited values(ie. the edited cell values and the new row added before saving) using "reload" functionality nothing happens in the grid.It remains as same with the edited values and the empty new row...
My code is here
$scope.init = function() {
var grid = $("#list");
var lastSel, dataSel, dataLen;
var colD, colM, colN, userdata;
jQuery.ajax({
async: false,
type: "GET",
url:"getData.htm",
data: "",
dataType: "json",
success: function(result){
colD = result.colData,
colM = result.colModel,
colN = result.colNames,
userdata = colD.userdata;
jQuery("#list").jqGrid({
datatype: 'local',
data: colD.rootVar,
colModel:colM,
sortorder: 'asc',
viewrecords: true,
resizable: true,
gridview: true,
altRows: true,
cellEdit:true,
footerrow: true,
scrollbar: true,
overflow: scroll,
scrollrows: true,
loadonce:true,
autowidth: true,
shrinkToFit: false,
editurl: 'clientArray',
cellsubmit: 'clientArray',
afterEditCell: function (id,name,val,iRow,iCol){
},
afterSaveCell : function(rowid,name,val,iRow,iCol) {
var updtd = jQuery("#list").jqGrid('getCol', name, false, 'sum');
var objs = [];
objs[name] = updtd;
jQuery("#list").jqGrid('footerData','set',objs);
},
loadComplete: function(data){
jQuery("#list").jqGrid('footerData','set',{'Employer':'Max Guest Count:'});
var colnames = jQuery("#list").jqGrid ('getGridParam', 'colModel');
dataLen = colnames.length;
dataSel = colnames[3]['name'];
for (var i = 3; i < colnames.length; i++){
var tot = jQuery("#list").jqGrid('getCol', colnames[i]['name'], false, 'sum');
var ob = [];
ob[colnames[i]['name']] = tot;
jQuery("#list").jqGrid('footerData','set',ob);
}
var ids = grid.getDataIDs();
for (var i = 0; i < ids.length; i++) {
grid.setRowData ( ids[i], false, {height: 25} );
}
jQuery ("table.ui-jqgrid-htable", jQuery("#list")).css ("height", 30);
},
gridComplete: function () {
jQuery("#list").jqGrid('setColProp','id',{width:20});
jQuery("#list").jqGrid('setColProp','Employer',{width:80});
jQuery("#list").jqGrid('setColProp','Sponsor',{width:80});
var tabs = $("#tabs");
var width = tabs.width();
jQuery("#list").jqGrid('setGridWidth', width - 80, true);
jQuery("#list").jqGrid('setGridHeight', 270);
},
});
},
});
jQuery("#list").jqGrid('setGroupHeaders', {
useColSpanStyle: true,
groupHeaders:[
{startColumnName: 'id', numberOfColumns: 1, titleText: ''},
{startColumnName: 'Employer', numberOfColumns: 2, titleText: ''},
{startColumnName: dataSel, numberOfColumns: dataLen, titleText: '<Strong><font color="white">Here Comes</font></Strong>'}
]
});
$("#addtn").click(function(){
var newRowData = {"Id":"","Employer":"","Sponsor":"",col1:"",col2:"",col3:"",col4:"",col5:"",col6:"",col7:"",col8:"",col9:"",col10:"",col11:"",col12:"",col13:"",col14:"",col15:"",col16:"",col17:"",col18:"",col19:"",col20:""};
jQuery("#list").addRowData(0,newRowData,"first",1);
jQuery("#list").editRow(0,true);
});
$("#rstbtn").click(function(){
$("#list").jqGrid('setGridParam',{datatype:'json', page:1, current:true}).trigger('reloadGrid')
});
};
I will really appreciate if someone can advice on this..

Probably because of this line: loadonce:true, in jqgrid definition. Set it as false and try again.
And for reloading, try this code:
$( '#list' ).trigger( 'reloadGrid', [{ page: 1}] );

Below code worked for me, to load updated data from the array.
$('#grid').jqGrid('clearGridData');
$("#grid").jqGrid('setGridParam',{data: DataArr, datatype:'local'}).trigger('reloadGrid');

Related

jqGrid - How can i track the speed of local operations

I have received as a assignment create 2 applications, one optimized and one unoptimized and i am using free jqGrid to display the data from DB.
I have successfully created both but i would like to track the speed at witch the local operations are done(paging,search,sorting).
I have tried to set up events for each button that triggers the operations, but they dont seem to trigger... i was wondering if there is something better that is built into jqGrid that i could use or a advice that would help me resolve this.
My jqGrid code goes like this:
$(function () {
var colModelSettings = [
{name:'id', label:'id',key: true, hidden: true, width:10,sorttype:'number',editable: true},
{name:'judet',label:'Judet',width:70, align: 'center',editable:true},
{name:'localitate',label:'Localitate',width:80,editable:true,searchoptions: {sopt: ['eq','bw','ew','cn']},align: 'center'},
{name:'tipStrada',label:'tipStrada',editable:true,searchoptions: {sopt: ['eq','bw','ew','cn']},width:100,align: 'center' },
{name:'denumire',label:'denumire',editable:true,width:100,searchoptions: {sopt: ['eq','bw','ew','cn']},align: 'center'},
{name:'cod',label:'cod',width:90,editable:true,align: 'center'}
];
var beforeEvent = 0;
$("#gridAdrese").jqGrid({
pager: $("#pagerGrid"),
url: "/UnoptimizedProject/rest/fetchData",
datatype: "json",
mtype: "POST",
loadonce: true,
forceClientSorting:true,
height: window.innerHeight-250,
sortname: 'id',
ajaxGridOptions: { contentType: 'application/json; charset=utf-8' },
serializeGridData: function (postData) {
if (postData.searchField === undefined) postData.searchField = null;
if (postData.searchString === undefined) postData.searchString = null;
if (postData.searchOper === undefined) postData.searchOper = null;
return JSON.stringify(postData);
},
rowNum: 5000,
viewrecords: true,
loadComplete: function(){
if(beforeEvent !== undefined){
var afterEvent = new Date().getTime();
console.log(afterEvent- beforeEvent);
beforeEvent = 0;
}
},
sortorder: 'asc',
caption:'Coduri Postale Neoptimizat' ,
autowidth: true,
colModel: colModelSettings,
});
$("#gridAdrese").jqGrid('navGrid', "#pagerGrid", {edit:false, add:false, del:false, save:false, cancel:false, search:true, searchtext: 'Search', refresh: false});
$("#jqgh_gridAdrese_judet, #jqgh_gridAdrese_localitate, #jqgh_gridAdrese_tipStrada, #jqgh_gridAdrese_denumire, #jqgh_gridAdrese_cod ").on("click",function(){
beforeEvent = new Date().getTime();
console.log("Sorting");
})
$("#fbox_gridAdrese_search").on("click",function(){
beforeEvent = new Date().getTime();
console.log("searching");
});
$("#next_pagerGrid , #last_pagerGrid, #prev_pagerGrid, #first_pagerGrid").on("click",function(){
beforeEvent = new Date().getTime();
console.log("paging");
})
});
You can do about the following:
var startTime, measureTime = false, timeInterval,
startMesure = function () {
startTime = new Date();
measureTime = true;
};
startMesure();
$("#gridAdrese").jqGrid({
url: "/UnoptimizedProject/rest/fetchData",
...
onSortCol: function () {
startMesure();
},
onPaging: function (pgButton, options) {
//if (pgButton === "records") {
startMesure();
//}
},
searching: {
closeAfterSearch: true,
closeAfterReset: true,
closeOnEscape: true,
searchOnEnter: true,
beforeSearch: function () {
startMesure();
return false; // allow filtering
},
onSearch: function () {
startMesure();
},
onReset: function () {
startMesure();
},
},
loadComplete: function () {
if (measureTime) {
timeInterval = new Date() - startTime;
setTimeout(function () {
alert("Total loading time: " + timeInterval + "ms\nFull time: " +
(new Date() - startTime));
}, 50);
measureTime = false;
}
}
}).jqGrid("filterToolbar").jqGrid("navGrid");
We reset startTime with respect of startTime = new Date(); to the current time at the beginning of sorting, paging or filtering.

jqGrid getGridParam('colModel') missing information

I would like capture the colModel for my jqGrid when the page unloads and store it in session so the next time the user comes to the page it can be loaded automatically. But, the information returned by ('#contract_grid').getGridParam('colModel') is missing part or all of the information in searchoptions for the grid columns.
Any idea why this is or how to capture the full colModel? The grid works great on the initial load but without the other searchoptions params, the filter bar features/menus don't work when I refresh the page from the colModel stored in session.
Create the default colModel for the grid
var defaultColModel =
[
{name:'REQUESTID'
,index:'requestID'
,label:'Request ID'
,search:true
,stype:'text'
,width:75
,key:true
,hidden:false
},
{name:'REQUESTEDDATE'
,index:'requestedDate'
,label:'Request Date'
,sorttype:"date"
,search:true
,width:50
,searchoptions:{
dataInit:function(el){jQuery(el).daterangepicker(
{
arrows:false
, dateFormat:'yy-mm-dd'
, onClose: function(dateText, inst){ jQuery("#contract_grid")[0].triggerToolbar();}
, onOpen: function() {
jQuery('div.ui-daterangepickercontain').css({"top": jQuery('#mouseY').val() + 'px', "left": jQuery('#mouseX').val() + 'px' });
}
});
}
}
,hidden:false
},
{name:'BUSINESSOWNERPERSONID'
,index:'businessOwnerPersonID'
,label:'Business Owner'
,search:true
,stype:'select'
,width:100
,hidden:false
,searchoptions: {
dataUrl: 'cfc/com_common.cfc?method=getAjxPeople&role=businessOwnerPersonID',
buildSelect: function(resp) {
var sel= '<select><option value=""></option><option value="7583,1636">My Reports</option>';
var obj = $.parseJSON(resp);
$.each(obj, function() {
sel += '<option value="'+this['lk_value']+ '">'+this['lk_option'] + "</option>"; // label and value are returned from Java layer
});
sel += '</select>';
return sel;
},
dataEvents: [{
type: 'change',
fn: function(e) {
alert(this.value)
}
}]
}
}
];
When user navigates away from page, save the grid to session so it loads when they come back
$(window).on('beforeunload', function(){
takeSnapshot();
});
function takeSnapshot(){
var gridInfo = new Object();
gridInfo.colModel = jQuery('#contract_grid').getGridParam('colModel');
gridInfo.postData = jQuery('#contract_grid').jqGrid('getGridParam', 'postData');
var snapshotData = JSON.stringify(gridInfo);
$.ajax({
url: "actions/act_filter.cfc?method=takeSnapshot",
type: "POST",
async: false,
data: {gridName:'contract_grid'
,gridParamName:'contractGridParams'
,filterData:snapshotData
}
});
}
Create grid variable
var myGrid = jQuery("#contract_grid").jqGrid({
url: 'cfc/com_ajxRequestNew.cfc?method=getReqJSON&returnformat=json',
datatype: 'json',
postData: {filters: myFilters},
mtype: 'POST',
search: true,
colModel: defaultColModel,
altRows: true,
emptyrecords: 'NO CONTRACTS FOUND',
height: 400,
width: 1200,
sortname: lastSortName,
sortorder: lastSortOrder,
page: lastPage,
pager: jQuery('#report_pager'),
rowNum: lastRowNum,
rowList: [10,20,50,100],
viewrecords: true,
clearSearch: false,
caption: "Contracts Dashboard",
sortable: true,
shrinkToFit: false,
ajaxSelectOptions: {type: "GET"},
gridComplete: function() {
//set the selected toolbar filter values
var myFields = JSON.parse(myFilters);
//set fields in form at top. filter contains index value so get corresponding name value because its used in the column label #gs
if ( myFields['rules'].length > 0 ) {
for (var i=0; i < myFields['rules'].length; i++ ) {
$.each(defaultColModel, function(j) {
if(this.index == myFields['rules'][i]['field'] ) {
thisFieldName = this.name;
jQuery('#gs_' + thisFieldName).val( myFields['rules'][i]['data'] );
}
})
}
}
}
});
jQuery("#contract_grid").navGrid('#report_pager',{
edit:false,
add:false,
del:false,
search:false,
refresh:false
}).navButtonAdd("#report_pager",{ caption:"Clear",title:"Clear Filters", buttonicon :'ui-icon-trash',
onClickButton: function() {
jQuery.ajax({
url: "/assets/js/ajx_clearFilter.cfm?showHeader=0",
async: false,
type: "POST",
data: ({variableName:'session.contractGridParams'})
});
myGrid[0].clearToolbar();
}
}).navButtonAdd("#report_pager",{ caption:"Restore",title:"Restore Default Grid Columns and Filters", buttonicon :'ui-icon-refresh',
onClickButton: function() {
window.location = '?page=dsp_requestListingNew&clearSession=1';
}
}).navButtonAdd("#report_pager",{
caption: "Export",
title: "Export to Excel",
buttonicon :'ui-icon-document',
onClickButton: function(e){
jQuery("#contract_grid").jqGrid('excelExport',{url:'includes/act_requestListingExport.cfm'});
}
}).navButtonAdd("#report_pager",{
caption: "Columns",
buttonicon: "ui-icon-calculator",
title: "Select and Reorder Columns",
jqModal: true,
onClickButton: function(e){
$('#contract_grid').jqGrid('columnChooser', {
dialog_opts: {
modal: true,
minWidth: 470,
show: 'blind',
hide: 'explode'
}
});
}
}).navButtonAdd("#report_pager",{
caption: "Save",
title: "Save Snapshot",
buttonicon :'ui-icon-disk',
onClickButton: function(e){
takeSnapshot(0);
$('#fltrFrmLink').click();
}
});
jQuery("#contract_grid").jqGrid('filterToolbar', {
stringResult : true
, searchOnEnter : true
, autoSearch : true
, beforeClear : function() {
//set sortnames
var sn = jQuery("#contract_grid").jqGrid('getGridParam','sortname');
//set sort orders
var so = jQuery("#contract_grid").jqGrid('getGridParam','sortorder');
so = "desc";
//set grid params
jQuery("#contract_grid").jqGrid('setGridParam',{ sortorder:so, sortname:sn });
}
});
colModel returned by ('#contract_grid').getGridParam('colModel') on unload. searchoptions is missing everything for REQUESTEDDATE. Part of dataEvents and all of buildSelect are missing for BUSINESSOWNERPERSONID.
[{"name":"REQUESTID",
"index":"requestID",
"label":"Request ID",
"search":true,
"stype":"text",
"width":75,
"key":true,
"hidden":false,
"title":true,"lso":"",
"widthOrg":75,"resizable":true,"sortable":true},
{"name":"REQUESTEDDATE",
"index":"requestedDate",
"label":"Request Date",
"sorttype":"date",
"search":true,
"width":50,
"searchoptions:{},
"hidden":false,
"title":true,
"lso":"",
"widthOrg":50,
"resizable":true,
"sortable":true,"stype":"text"},
{"name":"BUSINESSOWNERPERSONID",
"index":"businessOwnerPersonID",
"label":"Business Owner",
"search":true,
"stype":"select",
"width":100,"hidden":false,
"searchoptions":{"dataUrl":"cfc/com_common.cfc?method=getAjxPeople&role=businessOwnerPersonID",
"dataEvents":[{"type":"change"}]},
"title":true,
"lso":"",
"widthOrg":100,
"resizable":true,
"sortable":true}]
JSON don't support serialization of functions. So the functions from searchoptions.dataInit, searchoptions.buildSelect and all other which you use in colModel will be discarded after you use JSON.stringify.
It's important to know which version of jqGrid/free jqGrid or Guriddo jqGrid JS you use. Starting with jqGrid 4.7 one can define template in colModel with string value (see the pull request). In the way you will have the main information in colModel which can be serialized using JSON.stringify.

jqGrid local filtering causing rowid to be set to null

Based on jqGrid Filtering Records solution, i implemented the filtering on local.
However i am unable to set the first row as selected.Looks the row ids have been set to null. I am not sure why this would happening.
Code is as below
$("#showMatchingRecords").click(function(e) {
e.preventDefault();
var grid = $("#WorkList"), filter,searchfiler;
searchfiler = "700677";
grid[0].p.search = true;
filter = { groupOp:'OR', rules: [] };
filter.rules.push({field:"Id",op:"eq",data:searchfiler});
$.extend(grid[0].p.postData, {filters:JSON.stringify(filter)});
grid.trigger("reloadGrid", [{page:1}]);
});
$("#showAllRecords").click(function(e) {
e.preventDefault();
var grid = $("#WorkList");
grid[0].p.search = false;
$.extend(grid[0].p.postData, { filters: "" });
grid.trigger("reloadGrid", [{page:1}]);
});
Here is my gridComplete method, I have tried the same with loadComplete as well
gridComplete : function() {
$("tr.jqgrow:odd").css("background", "#DDDDDC");
var grid = $("#WorkList");
var ids = grid.getDataIDs();
console.log('before ids....', ids);
for (var i = 0; i < ids.length; i++) {
grid.setRowData(ids[i], false, { height: 35 });
}
Here are my grid options:
caption: 'Records List',
width: 1000,
height: 200,
pager: $("#WorkListPager"),
rowNum: 50,
sortname: 'Name',
loadonce: true,
sortorder: "asc",
cellEdit: false,
viewrecords: true,
imgpath: '/Content/Themes/Redmond/Images',
autowidth: false,
onSelectRow: function (rowid, status, e) {
/* function */
}
To select the first row on every reload of the grid you need do the following
loadComplete: function () {
var $self = $(this);
if (this.rows.length > 1) { // test that grid is not empty
$self.jqGrid("setSelection", this.rows[1].id);
}
}
I strictly recommend you additionally to include gridview: true option (see the answer for details) in the grid and to replace gridComplete to the usage of rowattr (see the answer).

How to set schema and column property in Kendu Grid dynamically

I am using kendu grid with report data,grid is working perfectly in normal case but my problem is that column and schema property of grid will not be static, that's why i want to add it dynamically,but I am unable to set it.
Here is my code:
$(document).ready(function () {
var obj = {
fields: {
}
};
var Column1;
$("#grid").kendoGrid({
dataSource: {
type: "data",
transport: {
read: function (options) {
$.ajax({
type: "GET",
url: "http://localhost:3833/Service1.svc/GetJSON1",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
var t2 = msg.GetJSON1Result;
var data1 = $.parseJSON(t2.data);
Column1 = t2.columns;
var t11 = Column1;
obj = {
fields: {
}
};
$.each(Column1, function (i, value) {
obj.fields[value.field] = { type: "number" };
}
);
var Schema1 = {
model: obj
}
var gridDetails = $("#grid");
**//Setting schema to grid but it's not effective**
gridDetails.schema = Schema1;
**//Setting schema to grid but it's not effective**
gridDetails.columns = Column1;
options.success(data1);
options.success(Schema1);
options.success(Column1);
}
});
}
},
pageSize: 50,
serverFiltering: false ,
serverSorting: false,
serverPaging: false,
},
height: 550,
reorderable: true,
filterable: true,
sortable: true,
pageable: true,
scrollable: true,
resizable: true,
groupable: true
});
});
please help me. I am new to kendu
Regards,
Ajeet Kumar
To change the grid columns you need to destroy it first and then initialize it again. Here is some code:
var grid = $("#grid").data("kendoGrid");
var options = grid.options;
grid.destroy();
options.columns = [ /* set the columns */ ];
grid.destroy();
$("#grid").empty().kendoGrid(options);

JQGrid InlineNav delete option

I am using "inlineNav" for my jqgrid. It has all the required features for Addition, edit, Cancel add. but cant find anything for deletion. I tried using "navGrid" delete but then that gives error "error Status: 'Not Found'. Error code: 404".
So can something be done about it?
#Oleg I am counting for your help!!
Following your suggestion I created this code but it is not working!! Can you tell me what went wrong:
var jsonData;
var jsonData1;
var dropdownVal;
function createDataStructure()
{
var mData;
if (document.forms[0].gridData.value == "" )
"";
else
mData = document.forms[0].gridData.value
jsonData = {
"rows": [ mData ]
};
dropdownVal = "12345:Party;12346:Miscellaneous;12347:Conveyance;12348:Staff Welfare";
}
function callGrid()
{
createDataStructure();
"use strict";
var webForm = document.forms[0],
mydata = "",
grid = $("#View1"),
lastSel,
getColumnIndex = function (columnName) {
var cm = $(this).jqGrid('getGridParam', 'colModel'), i, l = cm.length;
for (i = 0; i < l; i++) {
if ((cm[i].index || cm[i].name) === columnName) {
return i; // return the colModel index
}
}
return -1;
},
onclickSubmitLocal = function (options, postdata) {
var $this = $(this),
grid_p = this.p,
idname = grid_p.prmNames.id,
grid_id = this.id,
id_in_postdata = grid_id + "_id",
rowid = postdata[id_in_postdata],
addMode = rowid === "_empty",
oldValueOfSortColumn,
new_id,
tr_par_id,
colModel = grid_p.colModel,
cmName,
iCol,
cm;
// postdata has row id property with another name. we fix it:
if (addMode) {
// generate new id
new_id = $.jgrid.randId();
while ($("#" + new_id).length !== 0) {
new_id = $.jgrid.randId();
}
postdata[idname] = String(new_id);
} else if (typeof postdata[idname] === "undefined") {
// set id property only if the property not exist
postdata[idname] = rowid;
}
delete postdata[id_in_postdata];
// prepare postdata for tree grid
if (grid_p.treeGrid === true) {
if (addMode) {
tr_par_id = grid_p.treeGridModel === 'adjacency' ? grid_p.treeReader.parent_id_field : 'parent_id';
postdata[tr_par_id] = grid_p.selrow;
}
$.each(grid_p.treeReader, function (i) {
if (postdata.hasOwnProperty(this)) {
delete postdata[this];
}
});
}
// decode data if there encoded with autoencode
if (grid_p.autoencode) {
$.each(postdata, function (n, v) {
postdata[n] = $.jgrid.htmlDecode(v); // TODO: some columns could be skipped
});
}
// save old value from the sorted column
oldValueOfSortColumn = grid_p.sortname === "" ? undefined : grid.jqGrid('getCell', rowid, grid_p.sortname);
// save the data in the grid
if (grid_p.treeGrid === true) {
if (addMode) {
$this.jqGrid("addChildNode", new_id, grid_p.selrow, postdata);
} else {
$this.jqGrid("setTreeRow", rowid, postdata);
}
} else {
if (addMode) {
// we need unformat all date fields before calling of addRowData
for (cmName in postdata) {
if (postdata.hasOwnProperty(cmName)) {
iCol = getColumnIndex.call(this, cmName);
if (iCol >= 0) {
cm = colModel[iCol];
if (cm && cm.formatter === "date") {
postdata[cmName] = $.unformat.date.call(this, postdata[cmName], cm);
}
}
}
}
$this.jqGrid("addRowData", new_id, postdata, options.addedrow);
} else {
$this.jqGrid("setRowData", rowid, postdata);
}
}
if ((addMode && options.closeAfterAdd) || (!addMode && options.closeAfterEdit)) {
// close the edit/add dialog
$.jgrid.hideModal("#editmod" + grid_id, {
gb: "#gbox_" + grid_id,
jqm: options.jqModal,
onClose: options.onClose
});
}
if (postdata[grid_p.sortname] !== oldValueOfSortColumn) {
// if the data are changed in the column by which are currently sorted
// we need resort the grid
setTimeout(function () {
$this.trigger("reloadGrid", [{current: true}]);
}, 100);
}
// !!! the most important step: skip ajax request to the server
options.processing = true;
return {};
},
editSettings = {
//recreateForm: true,
jqModal: false,
reloadAfterSubmit: false,
closeOnEscape: true,
savekey: [true, 13],
closeAfterEdit: true,
onclickSubmit: onclickSubmitLocal
},
addSettings = {
//recreateForm: true,
jqModal: false,
reloadAfterSubmit: false,
savekey: [true, 13],
closeOnEscape: true,
closeAfterAdd: true,
onclickSubmit: onclickSubmitLocal
},
delSettings = {
// because I use "local" data I don't want to send the changes to the server
// so I use "processing:true" setting and delete the row manually in onclickSubmit
onclickSubmit: function (options, rowid) {
var $this = $(this), grid_id = $.jgrid.jqID(this.id), grid_p = this.p,
newPage = grid_p.page;
// reset the value of processing option to true to
// skip the ajax request to 'clientArray'.
options.processing = true;
// delete the row
if (grid_p.treeGrid) {
$this.jqGrid("delTreeNode", rowid);
} else {
$this.jqGrid("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.
$this.trigger("reloadGrid", [{page: newPage}]);
}
return true;
},
processing: true
},
initDateEdit = function (elem) {
setTimeout(function () {
$(elem).datepicker({
dateFormat: 'dd-M-yy',
//autoSize: true,
showOn: 'button',
changeYear: true,
changeMonth: true,
showButtonPanel: true,
showWeek: true
});
}, 100);
},
initDateSearch = function (elem) {
setTimeout(function () {
$(elem).datepicker({
dateFormat: 'dd-M-yy',
//autoSize: true,
//showOn: 'button', // it dosn't work in searching dialog
changeYear: true,
changeMonth: true,
showButtonPanel: true,
showWeek: true
});
}, 100);
};
grid.jqGrid({
datatype: "local",
data: jsonData.rows,
localReader: {
repeatitems: false,
id: "1"
},
colNames: ['Date','Expense Head','Amount', 'Reason','Remarks'],
colModel: [
{name:'sdate', index:'sdate', width:200, sorttype: 'date',
formatter: 'date', formatoptions: {newformat: 'd-M-Y'},
editable: true, datefmt: 'd-M-Y',
editoptions: {dataInit: initDateEdit, size: 14},
searchoptions: {dataInit: initDateSearch},
editrules: {required: true} },
{name:'expHead', index:'expHead', width:150, editable:true, sortable:true, edittype:"select", editoptions:{value:dropdownVal}, editrules: {required: true} },
{name:'expAmt', index:'expAmt', width:100, editable:true, summaryType:'sum', editrules: {required: true} },
{name:'expReason', index:'expReason', width:200, editable: true,edittype:"textarea", editoptions:{rows:"2",cols:"30"}, editrules: {required: true} },
{name:'expRemark', index:'expRemark', width:200,editable: true,edittype:"textarea", editoptions:{rows:"2",cols:"30"} }
],
loadtext: "Loading...",
sortname: 'sdate',
sortorder: 'desc',
pager: '#pView1',
caption: "Expense Table",
gridview: true,
rownumbers: true,
autoencode: true,
ignoreCase: true,
viewrecords: true,
footerrow: true,
height: "250",
editurl: 'clientArray',
beforeSelectRow: function (rowid) {
if (rowid !== lastSel) {
$(this).jqGrid('restoreRow', lastSel);
lastSel = rowid;
}
return true;
},
ondblClickRow: function (rowid, ri, ci) {
var $this = $(this), p = this.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"
$this.jqGrid('setSelection', rowid);
}
$this.jqGrid('editGridRow', rowid, editSettings);
},
onSelectRow: function (id) {
if (id && id !== lastSel) {
// cancel editing of the previous selected row if it was in editing state.
// jqGrid hold intern savedRow array inside of jqGrid object,
// so it is safe to call restoreRow method with any id parameter
// if jqGrid not in editing state
if (typeof lastSel !== "undefined") {
$(this).jqGrid('restoreRow', lastSel);
}
lastSel = id;
}
},
loadComplete: function () {
var sum = grid.jqGrid('getCol', 'expAmt', false, 'sum');
grid.jqGrid('footerData','set', {ID: 'Total:', expAmt: sum});
jsonData1 = grid.jqGrid('getGridParam', 'data');
document.forms[0].gridData.value = JSON.stringify(jsonData1);
},
loadError: function (jqXHR, textStatus, errorThrown) {
alert('HTTP status code: ' + jqXHR.status + '\n' +
'textStatus: ' + textStatus + '\n' +
'errorThrown: ' + errorThrown);
alert('HTTP message body (jqXHR.responseText): ' + '\n' + jqXHR.responseText);
}
});
grid.jqGrid('navGrid', '#pView1', {}, editSettings, addSettings, delSettings, {reloadAfterSubmit:true, beforeSubmit:validate_edit}, {reloadAfterSubmit:true, beforeSubmit:validate_add}, {}, {});
}
I am not providing any data but the same will come after it has been saved in the field and will be reloaded. But when I click on Add the form opens up and when I click on Submit after entering data it just stops. So can you tell me what must be wrong with my code!
Thanks for your help you are such a savior!!!
Siddhartha
inlineNav don't support Delete button, but you can use the corresponding button from navGrid. The problem is only that navGrid add button which implemented by form editing and form editing don't support editing local grid (editurl: 'clientArray') out-of-the-box.
In the old answer I suggested one way how one can do implement delete operation in form editing. In the answer I posted even the way how form editing can be used with local data. Another answer contains updated code which work with the current version (4.4.1 and 4.4.4) of jqGrid. I recommend you to use delSettings from the answer.

Resources