Free Jqgrid and custom formatter checkbox - jqgrid

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);
});

Related

page not loading on button click but works on link button in jqGrid in MVC

I have a page (Steps_Details.cshtml) with a jqgrid in MVC that i want to call it in 3 ways and it loads data based on the Unique_code i send as parameter. 1st way) i have another page (Rep_Contracts_Steps.cshtml) with a jqgrid and i have a link button in it and by clicking on this link button and sending the parameter data loads properly. 2nd way) a link on main menu with no parameters and it loads all data with no filtering.
the 3rd way and the one I've encountered problem with ) i have a button in a page and i send the parameter. it directs to the view but doesn't load the page.(in fact it doesn't call the "Get_Contracts_Steps_Details" Action in my HomeController when i use btnRep)
"Steps_Details.cshtml"
<script type="text/javascript">
$(document).ready(function () {
$('#list').jqGrid({
caption: "گزارش جزییات پیگیری قراردادها",
url: '#Url.Action("Get_Contracts_Steps_Details","Home")',
datatype: 'json',
jsonReader: {
root: "Rows",
page: "Page",
total: "Total",
records: "Records",
repeatitems: true,
userdata: "UserData",
id: "Vahed_Descript",
cell: "RowCells"
},
mtype: 'GET',
//columns names
colNames: [' ردیف ',
' کد تایید ',
' عنوان تایید ',
' کاربر تایید کننده ',
' تاریخ تایید ',
' توضیحات',
' کاربر ثبت کننده',
' تاریخ ثبت',
' کاربر ویرایش کننده' ,
' تاریخ ویرایش' ,
' عنوان واحد ',
' کد دبیرخانه ',
' شماره درخواست ',
' شرح درخواست ',
' تاریخ ثبت درخواست',
' مبلغ برآوردی ',
''
],
//columns model
colModel: [
{ name: 'MCS_ID', index: 'MCS_ID', align: 'Right', width: "60px", editable: true, editoptions: { readonly: "readonly" } },
{ name: 'MCS_ConfirmId', index: 'MCS_ConfirmId', align: 'Right', width: "60px", editable: false },
{ name: 'MWL_Descript', index: 'MWL_Descript', align: 'Right', editable: false },
{ name: 'MCS_ConfirmUser', index: 'MCS_ConfirmUser', align: 'Right', editable: true, edittype: 'text' },
{ name: 'MCS_ConfirmDate', index: 'MCS_ConfirmDate', align: 'Right', width: "80px", editable: true, edittype: 'text',
editrules: { required: true }
},
{ name: 'MCS_Note', index: 'MCS_Note', align: 'Right', width: "300px", editable: true, edittype: 'text' },
{ name: 'MCS_CreatorUserName', index: 'MCS_CreatorUser', align: 'Right', editable: false },
{ name: 'MCS_Creation_Date', index: 'MCS_Creation_Date', align: 'Right', width: "80px", editable: false },
{ name: 'MCS_EditorUserName', index: 'MCS_EditorUserName', align: 'Right', editable: false },
{ name: 'MCS_EditDate', index: 'MCS_EditDate', align: 'Right', width: "80px", editable: false },
{ name: 'DESCRIPT', index: 'DESCRIPT', align: 'right', editable: false },
{ name: 'DABIR_VAHED_CODE', index: 'DABIR_VAHED_CODE', align: 'right', width: "60px", editable: false },
{ name: 'CONTRACT_REQ_ID', index: 'CONTRACT_REQ_ID', align: 'right', width: "100px", editable: false },
{ name: 'CONTRACT_REQ_SUBJECT', index: 'CONTRACT_REQ_SUBJECT', align: 'right', editable: false },
{ name: 'D_CONTRACT_REQ', index: 'D_CONTRACT_REQ', align: 'right', width: "100px", editable: false },
{ name: 'AMNT_TOT_ESTIMATE', index: 'AMNT_TOT_ESTIMATE', align: 'right', width: "100px", editable: false,
formatter: 'currency', formatoptions:
{ decimalSeparator: '.', thousandsSeparator: ',', decimalPlaces: 0 }
},
{ name: 'MCS_REQ_UNIQUE', index: 'MCS_REQ_UNIQUE', width: 1, align: 'left', hidden: true },
],
pager: $('#pager'),
rowNum: 200,
rowList: [10, 20, 40, 60, 80, 100, 150, 200, 300],
sortname: 'CONTRACT_REQ_SUBJECT',
sortorder: 'asc',
viewrecords: true,
altRows: true,
shrinkToFit: false,
width: 'auto',
height: '300px',
hidegrid: false,
direction: "rtl",
gridview: true,
rownumbers: true,
footerrow: true,
userDataOnFooter: true,
scrollerbar: true,
loadComplete: function () {
$("tr.jqgrow:odd").css("background", "#E0E0E0");
},
loadError: function (xhr, st, err) {
jQuery("#rsperror").html("Type: " + st + "; Response: " + xhr.status + " " + xhr.statusText);
}
, loadonce: true
})
.jqGrid('navGrid', "#pager",
//enabling buttons
{ add: false, del: true, edit: true, search: true, refresh: true },
//edit option
{
url: '#Url.Action("EditSteps_Details", "Home")' ,
width: 'auto',
checkOnUpdate: true,
checkOnSubmit: true,
closeOnEscape: true,
closeAfterEdit: true,
beforeShowForm: function (form) {
centerDialog(form, $('#list'));
},
afterSubmit: function (response, postdata) {
$("#list").jqGrid('setGridParam', { datatype: 'json' }).trigger('reloadGrid');
return [true, "", ''];
},
afterComplete: function (response) {
if (response.responseText) {
alert(response.responseText);
}
}
},
//delete options
{
url: '#Url.Action("DeleteSteps_Details", "Home")', reloadAfterSubmit: false
, beforeShowForm: function (form) {
centerDialog(form, $('#list'));
},
});
function centerDialog(form, grid) {
var dlgDiv = $("#editmod" + grid[0].id);
var parentDiv = dlgDiv.parent(); // div#gbox_list
var dlgWidth = dlgDiv.width();
var parentWidth = parentDiv.width();
var dlgHeight = dlgDiv.height();
var parentHeight = parentDiv.height();
var parentTop = parentDiv.offset().top;
var parentLeft = parentDiv.offset().left;
dlgDiv[0].style.top = Math.round(parentTop + (parentHeight - dlgHeight) / 2) + "px";
dlgDiv[0].style.left = Math.round(parentLeft + (parentWidth - dlgWidth) / 2) + "px";
}
function toolbarSearching() {
$("#list").jqGrid('filterToolbar', {
autosearch: true,
stringResult: false,
searchOnEnter: true,
defaultSearch: "cn",
});
};
$("#list").jqGrid('filterToolbar', {
autosearch: true,
stringResult: false,
searchOnEnter: true,
defaultSearch: "cn",
});
var maxNameLength = 10;
$("input[id=gs_name]").blur(function () {
var $th = $(this).closest(".ui-search-toolbar>th"),
colIndex = $th[0].cellIndex,
$colHeader = $th.parent().siblings(".ui-jqgrid-labels").children("th").eq(colIndex),
colHeaderText = $colHeader.children("div").text();
if (this.value.length > maxNameLength) {
alert(colHeaderText + ' is longer than ' + maxNameLength + ' characters.');
}
});
$('#gs_invdate').datepicker({
changeMonth: true,
changeYear: true,
showButtonPanel: true
});
})
</script>
"Steps_Details" Action
[HttpGet]
public ActionResult Steps_Details(string REQ_UNIQE)
{
if (Session["LoginName"] == null)
{
return RedirectToAction("Index", "Home");
}
else
{
if (REQ_UNIQE != null)
{
if (REQ_UNIQE != "")
{
Session["REQ_UNIQE"] = REQ_UNIQE.ToString();
}
}
return View();
}
}
"button and the dropdownlist that i send the value of it as a parameter"
<div class="form-group">
#Html.DropDownListFor(model => model.Req_Unique, (SelectList)ViewBag.Contract_Req_Sub_List, "انتخاب", new { #class = "form-control", #id = "ddlContrReqSub", #onchange = "javascript:GetWork_Level(this.value);" })
<input type="button" name="submit" value="گزارش" id="btnRep" class="w3-button w3-MyDarkBlue w3-padding-large w3-margin-bottom" />
</div>
"javascript code for btnRep"
$(document).ready(function () {
$("#btnRep").click(function () {
var REQ_UNIQE = $("#ddlContrReqSub").val();
$.ajax({
url: "/Home/Steps_Details",
type: "GET",
data: { REQ_UNIQE: REQ_UNIQE },
});
});
});
"Get_Contracts_Steps_Details Action in HomeController"
[HttpGet]
public ActionResult Get_Contracts_Steps_Details(JqGridRequest request )
{
using (rw_mis_dbEntities dc = new rw_mis_dbEntities())
{
if (Session["REQ_UNIQE"] != null )
{
var list = dc.MVC_REP_Contracts_Steps_Details_By_Req_Unique(Security.SharedMembers.shrd_Year_Abbr, Security.SharedMembers.shrd_Vahed_Id, Security.SharedMembers.shrd_User_Id, "", "", 0, new Guid(Session["REQ_UNIQE"].ToString())).ToList();
var pageIndex = request.page - 1;
var pageSize = request.rows;
var totalRecords = list.Count;
var totalPages = (int)Math.Ceiling(totalRecords / (float)pageSize);
var contractsQuery = list.AsQueryable();
contractsQuery = new JqGridSearch().ApplyFilter(contractsQuery, request._search, request.searchField, request.searchString,
request.searchOper, request.filters, this.Request.Form);
if (string.IsNullOrWhiteSpace(request.oper))
{
contractsQuery = contractsQuery
.Skip(pageIndex * pageSize)
.Take(pageSize);
}
else if (request.oper == "excel")
{
contractsQuery = contractsQuery
.Skip(pageIndex * pageSize);
}
var contractsList = contractsQuery
.OrderBy(request.sidx + " " + request.sord)
.Skip(pageIndex * pageSize)
.Take(pageSize)
.ToList();
var jqGridData = new JqGridData
{
UserData = new // نمايش در فوتر
{
Name = "جمع صفحه"
},
Total = totalPages,
Page = request.page,
Records = totalRecords,
Rows = (contractsList.Select(Contract => new JqGridRowData
{
Id = Convert.ToInt32(Contract.MCS_ID),
RowCells = new List<string>
{ Contract.MCS_ID.ToString(),
Contract.MCS_ConfirmId.ToString(),
Contract.MWL_Descript,
Contract.MCS_ConfirmUser,
Contract.MCS_ConfirmDate.ToString() ,
Contract.MCS_Note ,
Contract.MCS_CreatorUserName.ToString() ,
Contract.MCS_CreationDate.ToString() ,
Contract.MCS_EditorUserName.ToString() ,
Contract.MCS_EditDate .ToString() ,
Contract.VAHED_DESCRIPT ,
Contract.DABIR_VAHED_CODE,
Contract.CONTRACT_REQ_ID ,
Contract.CONTRACT_REQ_SUBJECT ,
Contract.D_CONTRACT_REQ ,
Contract.AMNT_TOT_ESTIMATE.ToString() ,
Contract.MCS_REQ_UNIQUE.ToString ()
}
})).ToList()
};
Session["REQ_UNIQE"] = null;
return Json(jqGridData, JsonRequestBehavior.AllowGet);
}
else
{
var list = dc.MVC_REP_Contracts_Steps_Details(Security.SharedMembers.shrd_Year_Abbr, Security.SharedMembers.shrd_Vahed_Id, Security.SharedMembers.shrd_User_Id, "", "", 0 ).ToList();
var pageIndex = request.page - 1;
var pageSize = request.rows;
var totalRecords = list.Count;
var totalPages = (int)Math.Ceiling(totalRecords / (float)pageSize);
var contractsQuery = list.AsQueryable();
contractsQuery = new JqGridSearch().ApplyFilter(contractsQuery, request._search, request.searchField, request.searchString,
request.searchOper, request.filters, this.Request.Form);
if (string.IsNullOrWhiteSpace(request.oper))
{
contractsQuery = contractsQuery
.Skip(pageIndex * pageSize)
.Take(pageSize);
}
else if (request.oper == "excel")
{
contractsQuery = contractsQuery
.Skip(pageIndex * pageSize);
}
var contractsList = contractsQuery
.OrderBy(request.sidx + " " + request.sord)
.Skip(pageIndex * pageSize)
.Take(pageSize)
.ToList();
var jqGridData = new JqGridData
{
UserData = new // نمايش در فوتر
{
Name = "جمع صفحه"
},
Total = totalPages,
Page = request.page,
Records = totalRecords,
Rows = (contractsList.Select(Contract => new JqGridRowData
{
Id = Convert.ToInt32(Contract.MCS_ID),
RowCells = new List<string>
{ Contract.MCS_ID.ToString(),
Contract.MCS_ConfirmId.ToString(),
Contract.MWL_Descript,
Contract.MCS_ConfirmUser,
Contract.MCS_ConfirmDate.ToString() ,
Contract.MCS_Note ,
Contract.MCS_CreatorUserName.ToString() ,
Contract.MCS_CreationDate.ToString() ,
Contract.MCS_EditorUserName.ToString() ,
Contract.MCS_EditDate .ToString() ,
Contract.VAHED_DESCRIPT ,
Contract.DABIR_VAHED_CODE,
Contract.CONTRACT_REQ_ID ,
Contract.CONTRACT_REQ_SUBJECT ,
Contract.D_CONTRACT_REQ ,
Contract.AMNT_TOT_ESTIMATE.ToString() ,
Contract.MCS_REQ_UNIQUE.ToString ()
}
})).ToList()
};
return Json(jqGridData, JsonRequestBehavior.AllowGet);
}
}
}
Thanks in advance
I just changed
<input type="button" name="submit" value="گزارش" id="btnRep" class="w3-button w3-MyDarkBlue w3-padding-large w3-margin-bottom" />
To
<input type="button" name="submit" value="گزارش" id="btnRep" class="w3-button w3-MyDarkBlue w3-padding-large w3-margin-bottom" onclick="location.href='#Url.Action("Steps_Details", "Home")?Req_Unique=' + $('#ddlcontrreqsub').val()" />
and it worked
Method Get_Contracts_Steps_Details is with return type ActionResult. But jqGrid defined with datatype:'json'.
If Get_Contracts_Steps_Details is going to return json result for jqGrid, use return type string or JsonResult.

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

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!

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 textbox value not getting update

Problem: unable to get updatable value of textbox in jqgrid.
It just retrieve old value.
example - default value of textbox field inside jqgrid is - "0"
now, if i update its value to "1" and inspect the field then its value does not get updated into HTML and not able to retrieve with jqgrid object through below syntax.
var rowData = $('#gerList').jqGrid('getRowData', rowId);
Below is my jqgrid stuff:
$('#gerList').jqGrid({
ajaxGridOptions: {
error: function () {
$('#gerList')[0].grid.hDiv.loading = false;
alert('An error has occurred.');
}
},
url: '#Url.Action("GetEnrolls", "Attendance")/' + 0,
gridview: true,
autoencode: true,
postData: { adID: rowID },
datatype: 'json',
jsonReader: { root: 'List', page: 'Page', total: 'TotalPages', records: 'TotalCount', repeatitems: false, id: 'syStudentID' },
mtype: 'GET',
colNames: ['GrdID', 'name', 'Minutes', 'comment'],
colModel: [
{ name: 'syID', index: 'syID', hidden: true },
{ name: 'FullName', index: 'FullName', width: 150 },
{
name: 'Min', index: 'Min', width: 75, align: 'left', formatter: function (cellValue, option) {
return '<input type="text" style="width: 40px" name="txtMin" id="txt_' + option.rowId + '" value="' + cellValue + '" />';
}
},
{ name: 'MSG', index: 'MSG', width: 150 }
],
pager: $('#gerListPager'),
sortname: 'syStudentID',
rowNum: 40,
rowList: [40, 80, 120],
width: '525',
height: '100%',
viewrecords: true,
beforeSelectRow: function (rowid, e) {
console.log("final");
var $txt = $(e.target).closest('tr').find('input[type="text"]');
alert($txt);
$txt.attr('value', rowid);
return true; // allow row selection*/
return true;
},
sortorder: 'desc'
}).navGrid('#gerListPager', { edit: false, add: false, del: false, search: false, refresh: false });
Please suggest me what is wrong to use this textbox in jqgrid.
In grid UI, all fields are non editable except textbox field appear to allow edit always.
Thanks
Try to use this:
jQuery("#gerList").saveRow("rowid", false, 'clientArray');

Resources