jqGrid checkbox grouping summary - jqgrid

i would like to ask somebody if is there chance to change summary in header when user will check/uncheck the checkboxes. I created function to make total sum and print it into label (for this moment i skipped solving problem with groups).
Somewhere i found some solution like discart header and generate it again, but its was just for main header, not for group headers
Here is my example code
$(document).ready(function () {
$("#jqGrid").jqGrid({
url: 'data2.json',
mtype: "GET",
datatype: "json",
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,
formatter: 'number',
summaryTpl: "Total Units {0}", // set the summary template to show the group summary
summaryType: "sum" // set the formula to calculate the summary type
},
{ label: 'Ship Name', name: 'ShipName', width: 150 }
],
loadonce: true,
width: 900,
height: 500,
rowNum: 20,
rowList: [20, 30, 50],
sortname: 'OrderDate',
pager: "#jqGridPager",
viewrecords: true,
multiselect: true,
grouping: true,
userDataOnFooter: true,
onSelectRow: function (rowId) { handleSelectedRow(rowId); },
groupingView: {
groupField: ["CustomerID"],
groupColumnShow: [true],
groupText: ["<b>{0}</b>"],
groupOrder: ["asc"],
groupSummary: [true],
groupSummaryPos: ['header'],
groupCollapse: false
},
gridComplete: function () {
currids = $(this).jqGrid('getDataIDs');
}
});
});
var totalAmt=0;
function handleSelectedRow(id) {
var jqgcell = jQuery('#jqGrid').getCell(id, 'OrderID');
var amount = jQuery('#jqGrid').getCell(id, 'Freight');
var cbIsChecked = jQuery("#jqg_jqGrid_" + jqgcell).prop('checked');
if (cbIsChecked == true) {
if (amount != null) {
totalAmt = parseInt(totalAmt) + parseInt(amount);
}
} else {
if (amount != null) {
totalAmt = parseInt(totalAmt) - parseInt(amount);
}
}
$("#price").html(totalAmt);
}

I find this requirement very interesting and have prepared a demo. Of course this demo require a lot of other checking and optimizations, but it is a direction of haw to implement the requirement.
There are some notable settings and events: I assume that all rows are selected and when paging, sorting and etc we resett the selection (selectarrrow parameter) in beforeProcessing event.
The onSelectRow event is a little bit complicated, but this is required since of the current implementation.
Thanks of you, we have another directions of adding new features and improvements in Guriddo jqGrid.
Here is a demo
and below the code:
$(document).ready(function () {
$("#jqGrid").jqGrid({
url: 'data.json',
mtype: "GET",
datatype: "json",
colModel: [
{ label: 'OrderID', name: 'OrderID', key: true, width: 155 },
{ label: 'Customer ID', name: 'CustomerID', width: 70 },
{ label: 'Order Date', name: 'OrderDate', width: 150 },
{
label: 'Freight',
name: 'Freight',
width: 150,
formatter: 'number',
summaryTpl : "<b>{0}</b>",
summaryType: "sum"
},
{ label: 'Employee ID', name: 'EmployeeID', width: 150 }
],
loadonce:true,
viewrecords: true,
rowList: [20,30,50],
width: 780,
height: 250,
rowNum: 20,
multiselect : true,
sortname: 'OrderDate',
pager: "#jqGridPager",
grouping: true,
beforeProcessing: function(data) {
// reset the seleted rows after any seoring paging and ets.
this.p.selarrrow =[];
// put the new rows as selected
for(var i=0;i<this.p.rowNum;i++) {
if(data.rows[i]) {
this.p.selarrrow.push(data.rows[i].OrderID);
}
}
return true;
},
preserveSelection : true,
onSelectRow : function( rowid, status, event ) {
var row = this.rows.namedItem( rowid );
// determine the row index of selected row
var index = row.rowIndex;
// determine the level of grouping
var groups = this.p.groupingView.groupField.length;
// groups have specified id
var groupsid = this.p.id+'ghead_';
var indexdata = [], sums=[], i;
index--;
// loop in reverse order to find the group headers
while(index > 0 || (groups-1) >= 0 ) {
var searchid = groupsid +(groups-1);
// if the current id is a current group
if( this.rows[index] && this.rows[index].id.indexOf(searchid) !== -1) {
groups--;
// save the index of the parent group
indexdata[groups] = this.rows[index].rowIndex;
// put the sum of the Freigth (note that this is index 4)
sums[groups] = $(this.rows[row.rowIndex].cells[4]).text();
}
index--;
}
for(i=0;i<indexdata.length; i++) {
// fet the sum of the group
var suma = $(this.rows[indexdata[i]].cells[3]).text();
// if selected increase
if(status) {
suma = parseFloat(suma) + parseFloat(sums[i]);
} else {
suma = parseFloat(suma) - parseFloat(sums[i]) ;
}
// set the new calcculated value
$(this.rows[indexdata[i]].cells[3]).html( '<b>'+suma.toFixed(2)+'</b>' );
}
},
groupingView: {
groupField: ["CustomerID", "EmployeeID"],
groupColumnShow: [true, true],
groupText: [
"CustomerID: <b>{0}</b>",
"EmployeeID: <b>{0}</b>"
],
groupOrder: ["asc", "asc"],
groupSummary: [true, false],
groupSummaryPos: ['header', 'header'],
groupCollapse: false
}
});
});

thank you for your answer and your demo is exactly what i need. I tried to continue with code which I posted and for this moment i am inphase where user get total sum just for checked records. If somebody is interested about this solution then just replace below code. + One more thing about checkboxes and updates data in grid, the main checkbox which can check/uncheck all checkboxes is little bugy with sum calculation, if user will uncheck main checkbox then sum calculation is not reseted and then you can make another sums which are counted with previous calculations. But this can be fixed in code :)
thank you for you help Tony
var totalAmt = 0;
function handleSelectedRow(id) {
var jqgcell = jQuery('#list').getCell(id, 'id');
var amount = jQuery('#list').getCell(id, 'amount');
var cbIsChecked = jQuery("#jqg_list_" + jqgcell).prop('checked');
var getID = jQuery("#jqg_list_" + jqgcell).closest('tr').attr('id');
if (cbIsChecked == true) {
if (amount != null) {
totalAmt = parseInt(totalAmt) + parseInt(amount);
}
} else {
if (amount != null) {
totalAmt = parseInt(totalAmt) - parseInt(amount);
}
}
grid.jqGrid('footerData', 'set', { name: 'TOTAL', tax: totalAmt });
$("#price").html(totalAmt);
}

Related

Sorting issue with jqgrid

I want to implement sorting of visible rows in jqgrid the default behavior of jqgrid is sorting all records. i have handled it on server side but the problem is when i do sort i always get page as 1 even when i am on page2 or other.below is my code i also tried loadComplete, & onPaging method.
$(document).ready(function () {
$("#grid").jqGrid({
emptyrecords: "No records to view",
ignoreCase: true,
datatype: "json",
url: '#Url.Action("LoadData", "Home")',
mtype: "GET",
height: 'auto',
rowNum: 5,
rowList: [5, 10, 15, 20],
colNames: ['EmployeeId', 'EmployeeCity', 'EmployeeName'],
colModel: [
{ name: 'EmployeeId', index: 'EmployeeId', key: true, width: 200, sorttype: 'int' },
{ name: 'EmployeeName', index: 'EmployeeName', width: 200, sorttype: 'text' },
{ name: 'EmployeeCity', index: 'EmployeeCity', width: 200, sorttype: 'text' }
],
pager: '#pager',
sortname: 'EmployeeId',
viewrecords: true,
sortorder: "asc",
caption: "jqGrid Example"
}).navGrid("#pager",
{ search: false, refresh: false, add: false, edit: false, del: false },
{},
{},
{}
);
});
And , My server side code is ,
public ActionResult LoadData(int page, int rows, string sidx, string sord)
{
List<Employee> employeeList = new List<Employee>();
for (int i = 1; i < 18; i++)
{
employeeList.Add(
new Employee() { EmployeeId = i, EmployeeCity = "Mumbai_" + i, EmployeeName = "Jason_" + i }
);
}
var totalRecords = 0;
var totalPages = 0;
var griddata = new List<Employee>();
if (employeeList != null)
{
griddata = employeeList.Skip((page - 1) * rows).Take(rows).ToList();
switch (sidx.ToLower())
{
case "employeeid":
if (sord.ToLower() == "asc")
griddata.OrderBy(x => x.EmployeeId).ToList();
else
griddata.OrderByDescending(x => x.EmployeeId).ToList();
break;
default:
griddata.OrderByDescending(x => x.EmployeeName).ToList();
break;
}
totalRecords = employeeList.Count;
totalPages = (int)Math.Ceiling((double)totalRecords / (double)rows);
}
var employeeListData = new
{
total = totalPages,
page = page,
records = totalRecords,
rows = griddata,
};
return Json(employeeListData, JsonRequestBehavior.AllowGet);
}
You are ordering your data on server side after you get paging. I mean this section:
griddata = employeeList.Skip((page - 1) * rows).Take(rows).ToList();
switch (sidx.ToLower())
{
case "employeeid":
if (sord.ToLower() == "asc")
griddata.OrderBy(x => x.EmployeeId).ToList();
else
griddata.OrderByDescending(x => x.EmployeeId).ToList();
break;
default:
griddata.OrderByDescending(x => x.EmployeeName).ToList();
break;
}
Just change the order like this:
switch (sidx.ToLower())
{
case "employeeid":
if (sord.ToLower() == "asc")
employeeList = employeeList.OrderBy(x => x.EmployeeId).ToList();
else
employeeList = employeeList.OrderByDescending(x => x.EmployeeId).ToList();
break;
default:
employeeList = employeeList.OrderByDescending(x => x.EmployeeName).ToList();
break;
}
griddata = employeeList.Skip((page - 1) * rows).Take(rows).ToList();
Yes finally done in a simple way.
Added one hidden field.
<input type="hidden" id="exampleGrid" value="" />
Modified jqgrid as
$(document).ready(function () {
$("#grid").jqGrid({
emptyrecords: "No records to view",
ignoreCase: true,
datatype: "json",
url: '#Url.Action("LoadData", "Home")',
mtype: "GET",
height: 'auto',
rowNum: 5,
rowList: [5, 10, 15, 20],
colNames: ['EmployeeId', 'EmployeeName', 'EmployeeCity'],
colModel: [
{ name: 'EmployeeId', index: 'EmployeeId', key: true, width: 200, sorttype: 'int' },
{ name: 'EmployeeName', index: 'EmployeeName', width: 200, sorttype: 'text' },
{ name: 'EmployeeCity', index: 'EmployeeCity', width: 200, sorttype: 'text' }
],
pager: '#pager',
sortname: 'EmployeeId',
viewrecords: true,
loadComplete: function () {
var page = $('#grid').jqGrid('getGridParam', 'page');
$("#exampleGrid").val(page);
},
onSortCol: function (index, iCol, sortOrder) {
$('#grid').jqGrid('setGridParam', {
page: $("#exampleGrid").val()
});
},
sortorder: "asc",
caption: "jqGrid Example"
}).navGrid("#pager",
{ search: false, refresh: false, add: false, edit: false, del: false },
{},
{},
{}
);
});

jQGrid - "reloadGrid" - Keep Position

I'm trying to 'refresh' or 'reload' a grid and keep the row which has focus after the grid has been reloaded.
I've tried to do it as follows:-
var rowId = $("#dispatch").jqGrid('getGridParam','selrow');
var thisRow = (parseInt(rowId) + parseInt(1));
$("#dispatch").trigger("reloadGrid");
setTimeout(function(){
$("#dispatch").setSelection(thisRow);
}, 151);
But you can see it just from position #1 to the new position.
Is there any other way of reloading the grid and keeping focus position?
Tried:-
// Display Current Jobs
$('#btn-current').bind('click', function() {
$.ajax({
type: 'GET',
url: 'scripts/php/jobs.controller.php',
data: "id=" + "current",
success: function(data){
allButtons.removeClass('active');
$('#btn-current').addClass('active');
$("#dispatch").trigger("reloadGrid", [{current:true}]);
}
});
});
Grid:-
$(function () {
var lastsel2
var rowsToColor = [];
$("#dispatch").jqGrid({
url: 'scripts/xml/jobs.xml',
datatype: "xml",
xmlReader: {
root:"joblist",
row:"job",
repeatitems:false,
},
colNames: ["Time", "Car", "Status", "P", "Pickup", "Zone", "Destination", "Fare", "Name", "Type", "Tel", "Comments", "Account No", "Allow Time", "Tariff", "Email", "Driver Fare", "Driver Extras", "Customer Extras", "Driver", "Driver Comments", "Reference No", "Payment", "From No", "From Street", "From PostCode", "To No", "To Street", "To PostCode", "Account Name", "Flight No", "From Zone No", "To Zone No"],
colModel: [
{ name: "bookingdatetime", width: 55, editable: true },
{ name: "car", width: 45, editable: true },
{ name: "jbmessage", width: 60 },
{ name: "prebooking", width: 10 },
{ name: "pickup", width: 359, editable: true, classes:"grid-col"},
{ name: "zone", width: 50 },
{ name: "dropoff", width: 359, sortable: false, editable: true },
{ name: "customerfare", width: 76, editable: true },
{ name: "passname", width: 100, editable: true },
{ name: "cartype", width: 50, editable: true, },
{ name: "tel", width: 100, editable: true },
{ name: "comments", width: 150 },
{ name: "accountno", hidden: true },
{ name: "allowtime", hidden: true },
{ name: "tarif", hidden: true },
{ name: "emailaddress", hidden: true },
{ name: "driverfare", hidden: true },
{ name: "driverextras", hidden: true },
{ name: "customerextras", hidden: true },
{ name: "driver", hidden: true },
{ name: "comments1", hidden: true },
{ name: "referenceno", hidden: true },
{ name: "payment", hidden: true },
{ name: "fromno", hidden: true },
{ name: "fromstreet", hidden: true },
{ name: "frompostcode", hidden: true },
{ name: "tono", hidden: true },
{ name: "tostreet", hidden: true },
{ name: "topostcode", hidden: true },
{ name: "customer", hidden: true },
{ name: "flightno", hidden: true },
{ name: "fromzoneno", hidden: true },
{ name: "tozoneno", hidden: true }
],
loadComplete: function (){
var rowIds = $('#dispatch').jqGrid('getDataIDs');
for (i = 1; i <= rowIds.length; i++) {//iterate over each row
rowData = $('#dispatch').jqGrid('getRowData', i);
//set background style if Payment = Account
if (rowData['payment'] == 'Acc') {
$('#dispatch').jqGrid('setRowData', i, false, "yellow");
}
if (rowData['payment'] == 'CC') {
$('#dispatch').jqGrid('setRowData', i, false, "purple");
}
if (rowData['cartype'] == 'Est') {
$('#dispatch').jqGrid('setRowData', i, false, "green");
}
if (rowData['cartype'] == '8B' || rowData['cartype'] == 'Bus') {
$('#dispatch').jqGrid('setRowData', i, false, "red");
}
if (rowData['car'] == '00') {
$('#dispatch').jqGrid('setRowData', i, false, "cancel");
}
}
},
pager: "#pager",
loadui: 'disable',
rowNum: 50,
rowList: [10, 20, 30],
sortname: "invid",
sortorder: "desc",
viewrecords: true,
gridview: true,
autoencode: true,
width: null,
shrinkToFit: false,
height: 647,
scrollOffset: 0,
altRows:true,
altclass:'myAltRowClass',
onSelectRow: function (id, status) {
$('#txt-car-number').focus();
$('body').keyup(function (e) {
if (status && e.keyCode == 66 && $("#booking-docket").dialog("isOpen") === false) {
populateDocket();
$("#booking-docket").dialog('open');
}
});
},
gridComplete: function () {
$("#dispatch").setSelection(0, true);
},
});
$("#dispatch").jqGrid('setGridParam', {ondblClickRow: function(rowid,iRow,iCol,e){
populateDocket();
$("#booking-docket").dialog('open');
}});
$("#dispatch").jqGrid('bindKeys');
function populateDocket() {
var rowId =$("#dispatch").jqGrid('getGridParam','selrow');
var rowData = jQuery("#dispatch").getRowData(rowId);
var bookingdatetime = rowData['bookingdatetime'];
var car = rowData['car'];
var fromno = rowData['fromno'];
var fromstreet = rowData['fromstreet'];
var frompostcode = rowData['frompostcode'];
var tono = rowData['tono'];
var tostreet = rowData['tostreet'];
var topostcode = rowData['topostcode'];
var customerfare = rowData['customerfare'];
var passname = rowData['passname'];
var cartype = rowData['cartype'];
var tel = rowData['tel'];
var comments = rowData['comments'];
var accountno = rowData['accountno'];
var allowtime = rowData['allowtime'];
var tariff = rowData['tarif'];
var email = rowData['emailaddress'];
var driverFare = rowData['driverfare'];
var driverExtras = rowData['driverextras'];
var customerExtras = rowData['customerextras'];
var driver = rowData['driver'];
var commentsdrv = rowData['comments1'];
var referenceno = rowData['referenceno'];
var payment = rowData['payment'];
var accountname = rowData['customer'];
var flightno = rowData['flightno'];
var prebook = rowData['prebooking'];
var bookedby = rowData['bookedby'];
var date = bookingdatetime.split(' ');
var hour = date[1].substr(0,2)
var minute = date[1].substr(6,5)
$('#txt-date').val(date[0]);
$('#txt-hour').val(hour);
$('#txt-min').val(minute);
$('#txt-car').val(car);
$('#txt-pickup-hn').val(fromno);
$('#txt-pickup').val(fromstreet);
$('#txt-destination-hn').val(tono);
$('#txt-destination').val(tostreet);
$('#txt-client-fare').val(customerfare);
$('#txt-passenger').val(passname);
$('#txt-cartype').val(cartype);
$('#txt-telephone').val(tel);
$('#txt-general').val(comments);
$('#txt-account').val(accountno);
$('#txt-lead').val(allowtime);
$('#txt-tariff').val(tariff);
$('#txt-email').val(email);
$('#txt-drv-fare').val(driverFare);
$('#txt-account-name').val(accountname);
$('#txt-driver').val(driver);
$('#txt-office').val(commentsdrv);
$('#p-reference-no').html('-'+referenceno+'-');
$('#txt-payment').val(payment);
$('#txt-flight-no').val(flightno);
$('#txt-prebook').val(prebook);
$('#txt-bookedby').val(bookedby);
}
// Navigate Grids
$(document).keypress(function(e) {
if(e.keyCode == 40) { //down arrow
$('#nextElementId').click();
}
if(e.keyCode == 38) { //up arrow
$('#previousElementId').click();
}
});
$(document).keypress(function(e)
{
if(e.keyCode == 38 || e.keyCode == 40) //up/down arrow override
{
var gridArr = $('#dispatch').getDataIDs();
var selrow = $('#dispatch').getGridParam("selrow");
var curr_index = 0;
for(var i = 0; i < gridArr.length; i++)
{
if(gridArr[i]==selrow)
curr_index = i;
}
if(e.keyCode == 38) //up
{
if((curr_index-1)>=0)
$('#dispatch').resetSelection().setSelection(gridArr[curr_index-1],true);
}
if(e.keyCode == 40) //down
{
if((curr_index+1)<gridArr.length)
$('#dispatch').resetSelection().setSelection(gridArr[curr_index+1],true);
}
}
});
XML DATA:-
<?xml version="1.0"?>
<joblist resultcount="100">
<job id="0">
<pickup>26 CHIPPENHAM MEWS W9 2AN</pickup><dropoff>BREWER STREET W1F 0RJ</dropoff><bookingdatetime>14/05/2014 10:29:19</bookingdatetime><car></car><jbmessage></jbmessage><zone>MOUNTAIN</zone><customerfare>12</customerfare><passname>ele</passname><cartype>Car</cartype><tel>07771764901</tel><comments></comments><accountno></accountno><allowtime>10</allowtime><tarif>1</tarif><emailaddress></emailaddress><driverfare>12</driverfare><driverextras>0</driverextras><customerextras>0</customerextras><driver></driver><comments1></comments1><referenceno>221194</referenceno><payment>Cash</payment><fromno>26</fromno><fromstreet>CHIPPENHAM MEWS</fromstreet><frompostcode>W9 2AN</frompostcode><tono></tono><tostreet>BREWER STREET</tostreet><topostcode>W1F 0RJ</topostcode><prebooking>X</prebooking><customer></customer><flightno></flightno><bookedby>SAJJAD</bookedby><fromzoneno>27</fromzoneno><tozoneno>29</tozoneno></job><job id="1"><pickup>7 FOSBURY MEWS W23JE</pickup><dropoff>HEATHROW TER(T5) TW6 2GA</dropoff><bookingdatetime>13/05/2014 20:57:40</bookingdatetime><car>4</car><jbmessage>PAloc</jbmessage><zone>BALDWIN</zone><customerfare>41</customerfare><passname>BLOECKER</passname><cartype>MPV</cartype><tel>07435358308</tel><comments></comments><accountno></accountno><allowtime>15</allowtime><tarif>2</tarif><emailaddress></emailaddress><driverfare>41</driverfare><driverextras>0</driverextras><customerextras>0</customerextras><driver></driver><comments1></comments1><referenceno>220938</referenceno><payment>Cash</payment><fromno>7</fromno><fromstreet>FOSBURY MEWS</fromstreet><frompostcode>W23JE</frompostcode><tono></tono><tostreet>HEATHROW TER(T5)</tostreet><topostcode>TW6 2GA</topostcode><prebooking>X</prebooking><customer></customer><flightno></flightno><bookedby>SHEERAZ</bookedby><fromzoneno>21</fromzoneno><tozoneno>196</tozoneno>
</job>
</joblist>
Instead of usage setSelection inside of setTimeout you need just use additional parameter of reloadGrid: current:true. See the answer for more details.
UPDATED: The code of gridComplete seems be the reason of your problem:
$("#dispatch").setSelection(0, true);
it resets the selection of the grid after reloading to the row with the id="0".
I would strictly recommend you to replace the code of loadComplete to much more effective rowattr callback. See the answer for the corresponding code example.
Additionally you should not bind $('body').keyup on every row selection. In the way you bind (register) more and more new keyup event handles without unbinding the previous one. I'm not sure what you want to do in the part of the code, but you should probably move the code outside of onSelectRow callback.
I don't see any reason to set ondblClickRow with respect of setGridParam after the grid is created. Instead of that you can just include ondblClickRow callback directly in the list of jqGrid option during creating the grid (like you defined loadComplete, onSelectRow and gridComplete callbacks).
I recommend you to use $(this) instead of $('#dispatch') inside of any jqGrid callback.

JQGRID Performance issues

My Jqgrid is freezing after 500 rows, page is blocking and if rows exceeds 1000 or 1500 then one browser alert is coming and saying that "long time to execute script .. do you wanna stop or continue.. " I am in no mans land can you please check my code and suggest me.. Am I doing any wrong.
one more issue is Why my loading GIF image and page stuck until all rows loaded?
$(document).ready(function ()
{
GetTrackOrdersData();
});
var searchFilter = {};
searchFilter.REFERENCE = "%";
searchFilter.INVOICENOR = "";
searchFilter.PRODNAME = "ALL";
searchFilter.ORDSTATUS = "WIP";
------etc ------
function GetTrackOrdersData()
{
var param = JSON.stringify(
{
'searchFilter': searchFilter
}); //This function is from JSon2.js
$.ajax(
{
type: "POST",
url: "TrackOrdersNew.aspx/GetTrackOrdersData",
data: param,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (mydata)
{debugger;
var mydata = $.parseJSON(mydata.d);
if (mydata != null && mydata.length == 0)
{
$('#divgrid').hide();
$('#gbox_list1').hide();
$("#jqgridWrapperdiv").hide();
alert('No Records');
}
else if(mydata != null)
{
var i = 0;
for (i; i <= mydata.length; i++)
{
jQuery("#list1").jqGrid('addRowData', i + 1, mydata[i]);
}
if (i > 0)
{
$('.ui-jqgrid-title').text('Track Orders (' + (i - 1) + ')');
}
$("#jqgridWrapperdiv").hide();
$('#divgrid').show();
}
},
error: function (mydata)
{
alert("Some thing went wrong because of network. Please reload the page. Code:100T"+mydata.responseText);
$('#divgrid').hide();
},
complete: function ()
{
$("#jqgridWrapperdiv").hide();
}
});
}
function bindGrid()
{
jQuery("#list1").jqGrid(
{
datatype: "local",
colNames: ['Customer', 'Delivery', 'TrackNo','Ref', 'JobNo', 'Type', 'Product', 'Status',
'EntryDate', 'Scheduled', 'Invoiced'
],
colModel: [
{
name: 'CUOH_CUST_CD',
index: 'CUOH_CUST_CD',
width: 100,
classes: 'pointer'
},
{
name: 'CUOA_DEL_CUST_CD',
index: 'CUOA_DEL_CUST_CD',
width: 69,
classes: 'pointer'
},
{
name: 'CUOH_TRAK_NO',
index: 'CUOH_TRAK_NO',
width: 70,
classes: 'pointer'
},
{
name: 'CUOH_SOURCE_REF',
index: 'CUOH_SOURCE_REF',
width: 70,
classes: 'pointer'
},
{
name: 'CUOH_JOB_NO',
index: 'CUOH_JOB_NO',
width: 60,
classes: 'pointer'
},
{
name: 'CUOH_ORDER_TYPE',
index: 'CUOH_ORDER_TYPE',
width: 65,
classes: 'pointer'
},
{
name: 'CUOL_DESCR_LOC',
index: 'CUOL_DESCR_LOC',
width: 155,
classes: 'pointer'
},
{
name: 'Status',
index: 'Status',
width: 100,
classes: 'pointer',
cellattr: function (rowId, value)
{
// additional parameter of cellattr: rawObject, cm, rdata are optional
if (value.indexOf("ompleted")!=-1)
{
return ' class="bcolor"';
}
}
},
{
name: 'CUOH_ENTRY_DATE_TIME',
index: 'CUOH_ENTRY_DATE_TIME',
formatter: 'date',
formatoptions:
{
srcformat: 'd/m/Y',
newformat: 'd/m/Y'
},
width: 77,
classes: 'pointer'
},
{
name: 'CUOH_SCHEDULE_DATE',
index: 'CUOH_SCHEDULE_DATE',
formatter: 'date',
formatoptions:
{
srcformat: 'd/m/Y',
newformat: 'd/m/Y'
},
width: 84,
classes: 'pointer'
},
{
name: 'CUOH_INVOICE_DATE_TIME',
index: 'CUOH_INVOICE_DATE_TIME',
formatter: 'date',
formatoptions:
{
srcformat: 'd/m/Y',
newformat: 'd/m/Y'
},
width: 72,
classes: 'pointer'
}],
//multiselect: true,
//rowList: [10, 20, 30, 40],
//pager: jQuery('#pager1'),
//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: true, // disable current view record text like 'View 1-10 of 100'
rowNum: 10000,
sortorder: "asc",
caption: "Track Orders",
gridview: true,
//shrinkToFit: true,
loadui:"block",
loadonce: true,
rownumbers: true, //Displays Row number Column
onSelectRow: function (rowId)//ondblClickRow
{
var rowData = jQuery(this).getRowData(rowId);
var trackingNo = rowData['CUOH_TRAK_NO'];
RowClicked(trackingNo);
}
});
}
C sharp:
[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string GetTrackOrdersData(TrackOrdersFilterData searchFilter)
{
if (HttpContext.Current.Session["LoginName"] == null)
{
HttpContext.Current.Response.Redirect("~/Login.aspx");
}
string val = string.Empty;
DataSet ds = GetTrackOrders(searchFilter);
if (ds.Tables.Count > 0)
{
val = DataTableToJSON(ds.Tables[0]);
}
return val;
}

How to maintain checkbox selection while reloading the JQuery Grid?

I have a JQuery grid which I am reloading everytime when some event occurs on the server (i.e. update in the data set) and display the latest set of data in the grid. This grid has also got checkboxes in it's first column. What's happening is let's say user is selecting some checkboxes and in the meantime if the grid gets reloaded due to update in the data on the server, my grid gets reloaded with the latest set of data but all my previous checkbox selection gets lost. How can I mark these selected checkboxes again after grid reload?
Please suggest.
function PushData() {
// creates a proxy to the Alarm hub
var alarm = $.connection.alarmHub;
alarm.notification = function () {
$("#jqTable").trigger("reloadGrid",[{current:true}]);
};
// Start the connection and request current state
$.connection.hub.start(function () {
BindGrid();
});
}
function BindGrid() {
jqDataUrl = "Alarm/LoadjqData";
var selectedRowIds;
$("#jqTable").jqGrid({
url: jqDataUrl,
cache: false,
datatype: "json",
mtype: "POST",
multiselect: true ,
postData: {
sp: function () { return getPriority(); },
},
colNames: ["Id", "PointRef", "Value", "State", "Ack State", "Priority", "AlarmDate", "", ""],
colModel: [
//{ name: 'alarmId_Checkbox', index: 'chekbox', width: 100, formatter: "checkbox", formatoptions: { disabled: false }, editable: true, edittype: "checkbox" },
{ name: "AlarmId", index: "AlarmId", width: 70, align: "left" },
{ name: "PointRef", index: "PointRef", width: 200, align: "left" },
{ name: "Value", index: "Value", width: 120, align: "left" },
{ name: "AlarmStateName", index: "AlarmStateName", width: 150, align: "left" },
{ name: "AcknowledgementStateName", index: "AcknowledgementStateName", width: 200, align: "left" },
{ name: "Priority", index: "Priority", width: 130, align: "left" },
{ name: "AlarmDate", index: "AlarmDate", width: 250, align: "left" },
{ name: "TrendLink", index: "Trends", width: 100, align: "left" },
{ name: "MimicsLink", index: "Mimics", width: 100, align: "left" }
],
// Grid total width and height
width: 710,
height: 500,
hidegrid: false,
// Paging
toppager: false,
pager: $("#jqTablePager"),
rowNum: 20,
rowList: [5, 10, 20],
viewrecords: true, // "total number of records" is displayed
// Default sorting
sortname: "Priority",
sortorder: "asc",
// Grid caption
caption: "Telemetry Alarms",
onCellSelect: function (rowid, icol, cellcontent, e) {
var cm = jQuery("#jqTable").jqGrid('getGridParam', 'colModel');
var colName = cm[icol];
//alert(colName['index']);
if (colName['index'] == 'AlarmId') {
if ($("#AlarmDialog").dialog("isOpen")) {
$("#AlarmDialog").dialog("close");
}
AlarmDialogScript(rowid)
}
else if (colName['index'] == 'Trends') {
TrendDialogScript(rowid)
}
else if (colName['index'] == 'Mimics') {
MimicsDialogScript(rowid)
}
else {
$("#jqTable").setCell(rowid, "alarmId_Checkbox", true); //Selects checkbox while clicking any other column in the grid
}
},
recreateFilter: true,
emptyrecords: 'No Alarms to display',
loadComplete: function () {
var rowIDs = jQuery("#jqTable").getDataIDs();
for (var i = 0; i < rowIDs.length; i++) {
rowData = jQuery("#jqTable").getRowData(rowIDs[i]);
//change the style of hyperlink coloumns
$("#jqTable").jqGrid('setCell', rowIDs[i], "AlarmId", "", { 'text-decoration': 'underline', 'cursor': 'pointer' });
$("#jqTable").jqGrid('setCell', rowIDs[i], "TrendLink", "", { 'text-decoration': 'underline', 'cursor': 'pointer' });
$("#jqTable").jqGrid('setCell', rowIDs[i], "MimicsLink", "", { 'text-decoration': 'underline', 'cursor': 'pointer' });
if ($.trim(rowData.AcknowledgementStateName) == 'Active') {
$("#jqTable").jqGrid('setCell', rowIDs[i], "AcknowledgementStateName", "", { 'background-color': 'red', 'color': 'white' });
}
else if ($.trim(rowData.AcknowledgementStateName) == 'Acknowledged') {
$("#jqTable").jqGrid('setCell', rowIDs[i], "AcknowledgementStateName", "", { 'background-color': 'Navy', 'color': 'white' });
}
}
//$("#jqTable").jqGrid('hideCol', "AlarmId") //code for hiding a particular column
},
gridComplete: function () {
$('#jqTable input').bind('mouseover', function () {
var tr = $(this).closest('tr');
if ($("#AlarmDialog").dialog("isOpen")) {
$("#AlarmDialog").dialog("close");
}
AlarmDialogScript(tr[0].id);
}
);
}
}).navGrid("#jqTablePager",
{ refresh: true, add: false, edit: false, del: false },
{}, // settings for edit
{}, // settings for add
{}, // settings for delete
{sopt: ["cn"]} // Search options. Some options can be set on column level
)
.trigger('reloadGrid', [{page:1, current:true}]);
}
If I understand you correct you need just use additional parameter i
$("#list").trigger("reloadGrid", [{current:true}]);
or
$("#list").trigger("reloadGrid", [{page: 1, current: true}]);
(See the answer). It do almost the same what Justin suggested.
Depend from what you want exactly mean under reloading of the grid it can be that waht you need is to save the grid state inclusive the list of selected items in localStorage and reload the state after loading the grid. This answer describes in details the implementation. The corresponding demo from the answer could be simplified using new jqGrid events which are introduced in version 4.3.2.
You could save the selections before reloading the grid, for example in the beforeRequest event:
selectedRowIDs = jQuery('#myGrid').getGridParam('selarrrow');
Then after the grid has been reloaded, you can loop over selectedRowIDs and reselect each one using setSelection. For example:
for (i = 0, count = selectedRowIDs.length; i < count; i++) {
jQuery('#myGrid').jqGrid('setSelection', selectedRowIDs[i], false);
}
You might run this code in the loadComplete event.
use
recreateFilter: true
and you should be done

jqGrid Problem Binding Subgrid

I have a jqGrid that is not correctly displaying the subgrid rows. When I load the page, the regular grid rows display fine as well as the plus sign next to each of them, but when I click the plus button to expand them, the "Loading..." message just remains and nothing happens. I don't know if it makes a difference, but I am trying to do it on client side (loadonce: true).
Here is the code for creating the grid:
$("#Grid1").jqGrid({
// setup custom parameter names to pass to server
prmNames: {
search: null,
nd: null,
rows: "numRows",
page: "page",
sort: "sortField",
order: "sortOrder"
},
datatype: function(postdata) {
$(".loading").show(); // make sure we can see loader text
$.ajax({
url: 'WebServices/GetJSONData.asmx/getGridData',
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(postdata),
dataType: "json",
success: function(data, st) {
if (st == "success") {
var grid = $("#Grid1")[0];
grid.addJSONData(JSON.parse(data.d));
//Loadonce doesn't work, have to do its dirty work
$('#Grid1').jqGrid('setGridParam', { datatype: 'local' });
//After rows are loaded, have to manually load subgrid rows
var subgridData = JSON.parse(data.d).subgrid;
var lista = jQuery("#Grid1").getDataIDs();
var rowData;
//Iterate over each row in grid
for (i = 0; i < lista.length; i++) {
//Get current row data
rowData = jQuery("#Grid1").getRowData(lista[i]);
}
}
},
error: function() {
alert("Error with AJAX callback");
}
});
},
// this is what jqGrid is looking for in json callback
jsonReader: {
root: "rows",
page: "page",
total: "totalpages",
records: "totalrecords",
cell: "cell",
id: "id", //index of the column with the PK in it
userdata: "userdata",
repeatitems: true
},
coNames: ['Inv No', 'Amount', 'Store', 'Notes'],
colModel: [
{ name: 'InvNum', index: 'InvNum', width: 200 },
{ name: 'Amount', index: 'Amount', width: 55 },
{ name: 'Store', index: 'Store', width: 50 },
{ name: 'Notes', index: 'Notes', width: 100 }
],
subGrid: true,
subGridModel: [{
name: ['InvNum', 'Name', 'Qauntity'],
width: [55, 200, 80],
params: ['InvNum']
}],
rowNum: 10,
rowList: [10, 20, 50],
pager: '#Div1',
viewrecords: true,
width: 500,
height: 230,
scrollOffset: 0,
loadonce: true,
ignoreCase: true,
gridComplete: function() {
$(".loading").hide();
}
}).jqGrid('navGrid', '#Div1', { del: false, add: false, edit: false }, {}, {}, {}, { multipleSearch: true });
Here the code that I am using in the webservice call to create the JSON data:
IEnumerable orders = getOrders();
IEnumerable items = getItems();
int k = 0;
var jsonData = new
{
totalpages = totalPages, //--- number of pages
page = pageIndex, //--- current page
totalrecords = totalRecords, //--- total items
rows = (
from row in orders
select new
{
id = k++,
cell = new string[] {
row.InvNum.ToString(), row.Amount.ToString(), row.Store, row.Notes
}
}
).ToArray(),
subgrid = (
from row in items
select new
{
cell = new string[] {
row.InvNum.ToString(), row.Name, row.Quantity.ToString()
}
}
).ToArray()
};
result = Newtonsoft.Json.JsonConvert.SerializeObject(jsonData);

Resources