jqGrid add buttons for add/edit/delete in toolbar not working - jqgrid

I have tried to implement the code for adding buttons in jqGrid toolbar from the example site http://www.guriddo.net/demo/bootstrap/ but I'm surprised to find that it isn't working for me. Searched for a couple of hours but I can't figure it out. Here is my code:
<script type="text/javascript">
$(function () {
var gridDataUrl = '#Url.Action("JsonCategories", "AdminNomCategory")'
var grid = $("#reportsGrid").jqGrid({
url: gridDataUrl,
datatype: "json",
mtype: 'POST',
colNames: [
'#Html.DisplayNameFor(model => model.CategoryGuid)',
'#Html.DisplayNameFor(model => model.CategoryName)',
'#Html.DisplayNameFor(model => model.CategoryDescription)'
],
colModel: [
{ name: 'CategoryGuid', index: 'CategoryGuid', width: 10, align: 'left', classes: "nts-grid-cell", hidden: true },
{ name: 'CategoryName', index: 'CategoryName', width: 10, align: 'left', classes: "nts-grid-cell" },
{ name: 'CategoryDescription', index: 'CategoryDescription', width: 10, align: 'left', classes: "nts-grid-cell" }
],
rowNum: 20,
rowList: [10, 20, 30],
height: 450,
width: 1140,
pager: '#pager', /*jQuery('#pager'),*/
sortname: 'CategoryGuid',
toolbarfilter: true,
viewrecords: true,
sortorder: "asc",
caption: "Categories",
ondblClickRow: function (rowid) {
var gsr = jQuery("#reportsGrid").jqGrid('getGridParam', 'selrow');
if (gsr) {
var CategoryGuid = grid.jqGrid('getCell', gsr, 'CategoryGuid');
window.location.href = '#Url.Action("Edit", "AdminNomCategory")/' + CategoryGuid
}
else {
alert("Please select Row");
}
},
#*onSelectRow: function (rowid) {
var gsr = jQuery("#reportsGrid").jqGrid('getGridParam', 'selrow');
if (gsr) {
var CategoryGuid = grid.jqGrid('getCell', gsr, 'CategoryGuid');
window.location.href = '#Url.Action("Edit", "AdminNomCategory")/' + CategoryGuid
}
else {
alert("Please select Row");
}
}*#
});
//jQuery("#reportsGrid").jqGrid('navGrid', '#pager', { edit: true, add: true, del: true });
var template = "<div style='margin-left:15px;'><div> Customer ID <sup>*</sup>:</div><div> {CustomerID} </div>";
template += "<div> Company Name: </div><div>{CompanyName} </div>";
template += "<div> Phone: </div><div>{Phone} </div>";
template += "<div> Postal Code: </div><div>{PostalCode} </div>";
template += "<div> City:</div><div> {City} </div>";
template += "<hr style='width:100%;'/>";
template += "<div> {sData} {cData} </div></div>";
$('#reportsGrid').navGrid('#pager',
// the buttons to appear on the toolbar of the grid
{ edit: true, add: true, del: true, search: false, refresh: false, view: false, position: "left", cloneToTop: false },
//// options for the Edit Dialog
{
editCaption: "The Edit Dialog",
template: template,
errorTextFormat: function (data) {
return 'Error: ' + data.responseText
}
},
// options for the Add Dialog
{
template: template,
errorTextFormat: function (data) {
return 'Error: ' + data.responseText
}
},
// options for the Delete Dailog
{
errorTextFormat: function (data) {
return 'Error: ' + data.responseText
}
}
);
grid.jqGrid('filterToolbar', { searchOnEnter: true, enableClear: false });
jQuery("#pager .ui-pg-selbox").closest("td").before("<td dir='ltr'>Rows per page </td>");
grid.jqGrid('setGridHeight', $(window).innerHeight() - 450);
});
$(window).resize(function () {
$('#reportsGrid').jqGrid('setGridHeight', $(window).innerHeight() - 450);
});
</script>
I am using jqGrid 4.4.4 and ASP.NET. The thing I noticed, is that on the example page, the buttons are located inside a div with an id like 'jqGridPagerLeft', but on my page, that div has no id. So I went looking inside the jqGrid source but I'm lost and I can't figure out why it doesn't have an id allocated.
Any clues? I just want to add the buttons to the bottom toolbar. Thx!

Related

Free Jqgrid and custom formatter checkbox

When I click at last column checkbox, nothing happens.
//$.fn.jqm = false;
$.jgrid.jqModal = $.jgrid.jqModal || {};
$.extend(true, $.jgrid.jqModal, {toTop: true});
$("#Ecran").dialog({
//dialogClass: 'Ecran',
autoOpen: false,
width: 560,
height: 370,
modal: true,
open: function (event, ui) {
$("#jqGrid").jqGrid({
url: 'http://trirand.com/blog/phpjqgrid/examples/jsonp/getjsonp.php?callback=?&qwery=longorders',
mtype: "GET",
datatype: "jsonp",
colModel: [
{ label: 'OrderID', name: 'OrderID', key: true, width: 75 },
{ label: 'Customer ID', name: 'CustomerID', width: 150 },
{ label: 'Order Date', name: 'OrderDate', width: 150 },
{ label: 'Freight', name: 'Freight', width: 150 },
{ label:'Ship Name', name: 'ShipName', width: 150 },
{name:'ok',index:'ok', width:60,formatter:danu_094,align:'center',search:false}
],
cmTemplate: { width: 80, autoResizable: true },
autoResizing: { compact: true },
autoresizeOnLoad: true,
height: "auto",
viewrecords: true,
rownumbers:true,
//width: 480,
height: "200",
rowNum: 30,
rowList:[5,10,20,30,35],
pager: "#jqGridPager"
}).jqGrid("navGrid", { del: true, add: false, edit: false });
},
close:function () {}
});
$("#Ecran").dialog("open");
function danu_094 (val, options){
idrow=options.rowId;
var checked=(val == 'T') ? "checked='checked'" : "";
return '<input type="checkbox"' + checked + ' value="'+ val+ '" id='+ 'prel_'+idrow+' onchange="senddata_094('+idrow+')" /> ';
}
function senddata_094 (id){ //alert(id);
idelem=$('#prel_'+id);
if ((idelem).is(':checked')) idelem.val('T');
else idelem.val('F');
var sqldate = "&id="+id+"&preluat="+idelem.val();
alert(sqldate);
}
For demo please see http://jsfiddle.net/9ezy09ep/22/
It's unclear what you want to do with the code. In any way it contains many errors. For example you use
function danu_094 (val, options){
idrow=options.rowId;
var checked=(val == 'T') ? "checked='checked'" : "";
return '<input type="checkbox"' + checked + ' value="'+ val+ '" id='+ 'prel_'+
idrow+' onchange="senddata_094('+idrow+')" /> ';
}
where variable idrow is not declared. You should use " checked='checked'" instead of "checked='checked'".
The next problem: senddata_094 which you use needed be defined as global function. So you have to use for example
window.senddata_094 = function (id) {
...
}
or
senddata_094 = function (id){
...
}
where senddata_094 in not defined.
instead of
function senddata_094 (id){
...
}
The next problem: you use idelem variable inside of senddata_094.
By the way you can change ' onchange="senddata_094('+idrow+')" /> ' to ' onchange="senddata_094.call(this,'+idrow+')" /> '. It will initialize this inside of senddata_094 to the checkbox. You can use $(this) instead of $('#prel_'+id) in the senddata_094 function. Thus you will don't need to set any id attribute on the checkbox.
In the same you don't need to set any onchange attribute at all. Instead of that you can define change event on the grid level. The event handler will be called because of event bubbling:
$("#jqGrid").bind("change", function (e) {
var rowid = $(e.target).closest("tr.jqgrow").attr("id");
alert("changed id=" + rowid);
});

Cancel edit event in jqGrid inline edit

I'm using jqgrid inline edit in which i have a scenario to invoke the "cancel edit" button event and throw a message "Are you sure to cancel?".
//Code:
//Unload the grid.
$('#CommentsData').jqGrid('GridUnload');
//Comments grid start.
$("#CommentsData").jqGrid({
datastr: tableSrc,
hoverrows: false,
datatype: "jsonstring",
jsonReader: {
id: 'CommentId',
repeatitems: false
},
height: 'auto',
width: 'auto',
hidegrid: false,
gridview: true,
sortorder: 'desc',
sortname: 'DateTime',
pager: '#CommentsPager',
rowList: [], // disable page size dropdown
pgbuttons: false, // disable page control like next, back button
pgtext: null, // disable pager text like 'Page 0 of 10'
viewrecords: false, // disable current view record text like 'View 1-10 of 100'
caption: "Comments",
colNames: ['DateTime', 'UserName', 'Comments'],
colModel: [
{
name: 'DateTime', index: 'DateTime', width: 120, formatter: "date", sorttype: "date",
formatoptions: { srcformat: "ISO8601Long", newformat: "m/d/Y h:i A" }
},
{ name: 'UserName', index: 'UserName' },
{ name: 'CommentText', index: 'CommentText', editable: true }],
//Events to add and edit comments.
serializeRowData: function (postdata) {
var filterResult;
var jsonResult;
if (tableSrc == "")
jsonResult = $.parseJSON(commentDetails);
else
//Parse values bind to the comments.
jsonResult = $.parseJSON(tableSrc);
var newResult = new Object();
//Check if operation is edit.
if (postdata.oper == "edit") {
//Filter the edited comments from main source.
newResult = Enumerable.From(jsonResult).Where(function (s) { return s.CommentId = postdata.id }).First();
newResult.CommentText = postdata.CommentText;
}
else {
filterResult = Enumerable.From(jsonResult).First();
newResult.CommentText = postdata.CommentText;
newResult.TransactionId = filterResult.TransactionId;
newResult.TaskId = filterResult.TaskId;
}
filterResult = JSON.stringify(newResult);
$.ajax({
url: '#Url.Action("UpdateComments", "Home")',
datatype: 'json',
data: { 'resultData': filterResult, 'action': postdata.oper },
type: 'POST',
success: OnCompleteComments,
error: function (xhr, status, error) {
if (xhr.statusText == "Session TimeOut/UnAuthorized") {
alert(xhr.statusText);
window.location.href = '#Url.Action("LogOut", "Account")';
}
else
alert(xhr.responseText);
}
});
//After update Load the grid.
function OnCompleteComments(result) {
selectTaskComment = false;
$('#dialog').dialog("close");
myfilter = $("#TransactionsGrid").jqGrid("getGridParam", "postData").filters;
rowList = $('.ui-pg-selbox').val();
Loadgrid($("#TransactionsGrid").getGridParam('page'));
}
},
onSelectRow: function (id) {
selectTaskComment = true;
var thisId = $.jgrid.jqID(this.id);
$("#" + thisId + "_iledit").removeClass('ui-state-disabled');
$("#del_" + thisId).removeClass('ui-state-disabled');
var selectValues = jQuery('#CommentsData').jqGrid('getRowData', id);
thisId = $.jgrid.jqID(this.id);
if (selectValues.UserName == '#ViewBag.UserName' || '#ViewBag.IsAdmin' == 'True') {
$("#" + thisId + "_iledit").removeClass('ui-state-disabled');
$("#del_" + thisId).removeClass('ui-state-disabled');
}
else {
$("#" + thisId + "_iledit").addClass('ui-state-disabled');
$("#del_" + thisId).addClass('ui-state-disabled');
}
}
});
jQuery("#CommentsData").jqGrid('navGrid', '#CommentsPager', { edit: false, add: false, del: true, search: false, refresh: false }, {}, {},
{
//Delete event for comments
url: '#Url.Action("UpdateComments", "Home")',
serializeDelData: function (postData) {
return {
resultData: JSON.stringify(postData.id),
action: JSON.stringify(postData.oper),
}
},
errorTextFormat: function (xhr) {
if (xhr.statusText == "Session TimeOut/UnAuthorized") {
window.location.href = '#Url.Action("LogOut", "Account")';
} else {
return xhr.responseText;
}
},
beforeSubmit: function () {
myfilter = $("#TransactionsGrid").jqGrid("getGridParam", "postData").filters;
return [true, '', ''];
},
afterSubmit: function (response, postdata) {
selectTaskComment = false;
Loadgrid($("#TransactionsGrid").getGridParam('page'));
return [true, '', ''];
}
});
$('#CommentsData').jqGrid('inlineNav', '#CommentsPager', { edit: true, add: true, save: true, del: false, cancel: true });
$("#CommentsData_iledit").addClass('ui-state-disabled');
$("#del_CommentsData").addClass('ui-state-disabled');
In which event i have to write the code and throw the alert message?
Also if possible, need to know if the above code could be optimized. Because the delete event is written in a separate place comparing edit and add. I'm bit confused if this is right method.
The easiest way to invoke the "cancel edit" button would be executing the code
$("#CommentsData_ilcancel").click(); // trigger click event on Cancel button
where CommentsData is the id of the grid.

How to achieve edit and delete on jqgrid?

Below is my JQGrid code which is working fine for loading of grid, paging and sorting.
Now, I need to add - Edit and Delete functionality.
I found on google, to enable "edit" and "delete" option in navbar but,
I want it as like ---- User click on "a href" link and it should call javascritp function along with rowID . Can you guide me , how can i add hyper link and on click of it allow to call functino ?
$('#CategoriesGrdList').jqGrid({
ajaxGridOptions: {
error: function () {
$('#CategoriesGrdList')[0].grid.hDiv.loading = false;
alert('An error has occurred.');
}
},
url: '#Url.Action("GetAllCategoriesList", "Categories")/' + 0,
gridview: true,
autoencode: true,
//public JsonResult GetEnrolls(int adClassSchedID,DateTime attendanceDate,int adProgramID,int syCampusID)
postData: { categoryId: 1 },
//postData: { categoryId: rowID, attendanceDate: $('#AttendanceDate').val(), adProgramID: $('#adProgramID').val(), syCampusID: $('#syCampusID').val() },
datatype: 'json',
jsonReader: { root: 'List', page: 'Page', total: 'TotalPages', records: 'TotalCount', repeatitems: false, id: 'Id' },
mtype: 'GET',
colNames: ['Id', 'Code', 'Description', 'IsActive'],
colModel: [
{ name: 'Id', index: 'Id', hidden: true },
{ name: 'Code', index: 'Code', width: 170 },
{ name: 'Description', index: 'Description', width: 170 },
{ name: 'IsActive', index: 'IsActive', width: 170 }
],
pager: $('#CategoriesGrdPager'),
sortname: 'Code',
rowNum: 40,
rowList: [3, 3, 3],
width: '525',
height: '100%',
viewrecords: true,
beforeSelectRow: function (rowid, e) {
return false;
},
sortorder: 'desc'
}).navGrid('#CategoriesGrdPager', { edit: false, add: false, del: false, search: false, refresh: false });
});
NOTE:
As suggestion from one of comment below,
Added below column:
{
name: 'act', index: 'act', width: 55, align: 'center', sortable: false, formatter: 'actions',
formatoptions: {
keys: true, // we want use [Enter] key to save the row and [Esc] to cancel editing.
onEdit: function (rowid) {
alert("in onEdit: rowid=" + rowid + "\nWe don't need return anything");
},
onSuccess: function (jqXHR) {
// the function will be used as "succesfunc" parameter of editRow function
// (see http://www.trirand.com/jqgridwiki/doku.php?id=wiki:inline_editing#editrow)
alert("in onSuccess used only for remote editing:" +
"\nresponseText=" + jqXHR.responseText +
"\n\nWe can verify the server response and return false in case of" +
" error response. return true confirm that the response is successful");
// we can verify the server response and interpret it do as an error
// in the case we should return false. In the case onError will be called
return true;
},
onError: function (rowid, jqXHR, textStatus) {
// the function will be used as "errorfunc" parameter of editRow function
// (see http://www.trirand.com/jqgridwiki/doku.php?id=wiki:inline_editing#editrow)
// and saveRow function
// (see http://www.trirand.com/jqgridwiki/doku.php?id=wiki:inline_editing#saverow)
alert("in onError used only for remote editing:" +
"\nresponseText=" + jqXHR.responseText +
"\nstatus=" + jqXHR.status +
"\nstatusText" + jqXHR.statusText +
"\n\nWe don't need return anything");
},
afterSave: function (rowid) {
alert("in afterSave (Submit): rowid=" + rowid + "\nWe don't need return anything");
},
afterRestore: function (rowid) {
alert("in afterRestore (Cancel): rowid=" + rowid + "\nWe don't need return anything");
},
delOptions: {
// 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 (rp_ge, rowid) {
// we can use onclickSubmit function as "onclick" on "Delete" button
alert("The row with rowid=" + rowid + " will be deleted");
// reset processing which could be modified
rp_ge.processing = true;
// delete row
$(this).delRowData(rowid);
$("#delmod" + $(this)[0].id).hide();
if ($(this)[0].p.lastpage > 1) {
// reload grid to make the row from the next page visable.
// TODO: deleting the last row from the last page which number is higher as 1
$(this).trigger("reloadGrid", [{ page: $(this)[0].p.page }]);
}
return true;
},
processing: true // !!! the most important step for the "local" editing
// skip ajax request to the server
}
}
}
Now, PROBLEM:
Where to specify for calling - action of controller ?
On click of Edit, nothing happen, I want to call my own controlller 'action and popup my own dialog instead of jqgrid dialog.
PLease guide me.
I see you are using MVC, this is how I am doing it, this may be different than how you are doing it, but I like to do it this way. Basically you specify how you edit, add and delete in your controller and then use "url: '/YourController/YourActionMethod/' to tell the grid where to look. there are many different options you can set such as caption, width etc See Here.
}).navGrid('#CategoriesGrdPager', { cloneToTop: true, search: false },
{
url: '/YourController/EditCategories/',
editCaption: 'Edit Post',
closeAfterEdit: true,
closeOnEscape: true,
dataheight: 1150,
top: 25,
left: 50,
width: 900,
},//edit options
{
url: '/YourController/AddCategories/',
addCaption: 'New Post',
closeAfterAdd: true,
closeOnEscape: true,
dataheight: 1150,
top: 25,
left: 50,
width: 900,
},//add options
{
url: '/YourController/DeleteCategories/',
caption: 'Delete Post',
closeOnEscape: true,
}//delete options
);

Add check boxes in Jquery grid view

I have the following code in page which binds the data to j query grid.
Now i want to add one more column for check-boxes to the existing grid and when i select some check boxes and press some button .. i need to get the selected row values .
I have seen some tutorials for this they mentioned about some formatter .... but they are not clear
Please help me to achieve this.
Thanks in advance.
Code:
$(document).ready(function () {
$("#btn_GenerateEmpList").click(function () {
var firstClick = true;
if (!firstClick) {
$("#EmpTable").trigger("reloadGrid");
}
firstClick = false;
var empId= $("#txt_emp").val();
$.ajax({
type: "POST",
url: "PLBased.aspx/GetEmpNames",
data: JSON.stringify({ empId: empId}),
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result) {
result = result.d;
jQuery("#EmpTable").jqGrid({
datatype: "local",
colNames: ['Emp Name'],
colModel: [
{ name: "EmpName", Index: "EmpName", width: 80 }
],
data: JSON.parse(result),
rowNum: 10,
rowList: [5, 10, 20],
pager: '#pager',
loadonce: false,
viewrecords: true,
sortorder: 'asc',
gridview: true,
autowidth: true,
sortname: 'EMPID',
height: 'auto',
altrows: true,
});
},
error: function (result) {
alert("There was some error ");
}
});
});
});
You can use customformatter to show checkbox in the column. For this, you can write the code as below in your jqGrid Code.
colNames: ['Id','Emp Name','Emp Checkbox'],
colModel: [
{ name: 'Id', index: 'Id', hidden: true },
{ name: 'EmpName', Index: 'EmpName', width: 80 },
{ name: 'Empchk', Index: 'Empchk', width: 50, align: 'center', editable: true, edittype: "checkbox", editoptions: { value: "true:false" },
formatter: generateEmpCheckBox, formatoptions: { disabled: false } }
],
formatter function code as below,
function generateEmpCheckBox(cellvalue, options, rowObject) {
var checkedStr = "";
if (cellvalue == true) {
checkedStr = " checked=checked ";
}
return '<input type="checkbox" onchange="UpdateEmpcheckbox(' + rowObject.Id + ',this)" value="' + cellvalue + '" ' + checkedStr + '/>';
}
function UpdateEmpcheckbox(selectedId, chkBox) {
if ($(chkBox).prop("checked")) {
//you can write an ajax here, to update the server
//when the checkbox is checked
}
else if (!($(chkBox).prop("checked"))) {
//you can write an ajax here to update the server
//when the checkbox is unchecked
}
return false;
}
Set the option multiselect:true which will add column of checkboxes. Then add
$('#EmpTable').jqGrid('getGridParam', 'selarrrow')
will return an array of selected id's.

JqGrid Width resizing Issue with Browser resize

Can I set JqGrid width in a way that it automatically resizes with browser width.
Have tried using this.
autowidth:true,
.....
$(window).bind('resize', function () {
$("#table").setGridWidth($("#table").width());
}).trigger('resize');
Resizing isnt working as expected, When I resize the browser I expect grid to resize accordingly to that of browser width.
UPDATE:
$(function () {
$grid = $("#table");
$grid.jqGrid({
url: '../../Services/OrderService.asmx/getGlbOrders',
datatype: 'json',
mtype: 'POST',
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;
//if (postData.filters === undefined) postData.filters = null;
return JSON.stringify(postData);
},
jsonReader: {
root: "d.rows",
page: "d.page",
total: "d.total",
records: "d.records",
id: "d.names"
},
colModel: [
{ name: 'select', label: 'select', width: 50,
formatter: function radio(cellValue, option) {
return '<input type="radio" name="radio_' + option.gid + '" value=' + cellValue + ' />';
}
},
{ name: 'code', label: 'Order ID' },
{ name: 'qty', label: 'Quantity' },
{ name: 'qtyr', label: 'Remaining Qty'},
{ name: 'uts', label: 'Units' },
{ name: 'status', label: 'Status' },
],
rowNum: 10,
rowList: [10, 20, 300],
sortname: 'name',
sortorder: "asc",
pager: "#pager",
viewrecords: true,
gridview: true,
rownumbers: true,
height: 250,
autowidth: true,
caption: 'Global Order List'
}).jqGrid('navGrid', '#pager', { edit: false, add: false, del: false, search: false });
})
$(window).bind('resize', function () {
$("#table").setGridWidth($("#table").width());
}).trigger('resize');
change your code from:
$(function () {
$grid = $("#table");
$grid.jqGrid({
// etc..
}).jqGrid('navGrid', '#pager', { edit: false, add: false, del: false, search: false });
})
$(window).bind('resize', function () {
$("#table").setGridWidth($("#table").width());
}).trigger('resize');
to:
$(function () {
$grid = $("#table");
$grid.jqGrid({
// etc..
}).jqGrid('navGrid', '#pager', { edit: false, add: false, del: false, search: false });
});
$(window).bind('resize', function () {
$("#table").setGridWidth($("#table").width());
}).trigger('resize');
You have forgotten a semicolon after the end of your jqGrid function. Then the code that comes after your function is ignored.

Resources