jQGrid - "reloadGrid" - Keep Position - jqgrid

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.

Related

jqGrid checkbox grouping summary

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

Jqgrid cascading dropdown

Using jqgrid free latest version 4.15.2
I am trying to make cascading drop down from db.
I tried the sample as posted by #Oleg
jqgrid incorrect select drop down option values in edit box
But this is for older version of jqgrid and does not work fully while using latest version of jqgrid.
var countries = { "UsId": "US", "UkId": "UK" },
statesOfUS = { "AlabamaId": "Alabama", "CaliforniaId": "California", "FloridaId": "Florida", "HawaiiId": "Hawaii" },
statesOfUK = { "LondonId": "London", "OxfordId": "Oxford" },
states = $.extend({}, statesOfUS, statesOfUK),
allCountries = $.extend({"": "All"}, countries),
allStates = $.extend({"": "All"}, states),
// the next maps provide the states by ids to the contries
statesOfCountry = {
"": states,
"UsId": statesOfUS,
"UkId": statesOfUK
},
The entire code can be seen in fiddle below
https://jsfiddle.net/svnL4Lsv/
The issue is during the add form the second dropwdown shows all states instead of showing as per country
Secondly during the edit the second dropdown again shows all states and not as per the row value
Its just when I change the first dropdown does the second dropdown filters and works.
----------Updated
editoptions: {
// value: countries,
dataInit: dataInitApp,
dataEvents: dataEventsApp,
dataUrl: '#Url.Action("GetData", "Home")',
}
Controller code:
public enum Countries
{
USA = 1,
UK = 2
}
public enum State
{
Alabama = 1,
Florida = 2
London = 3
}
public JsonResult GetData()
{
var type = typeof(Helpers.UsersEnum.Countries);
var jsonData = Enum.GetNames(type)
.Select(name => new
{
Id = (int)Enum.Parse(type, name),
Name = name
})
.ToArray();
return Json(jsonData);
}
I call the above to populate my dropdown.
Also below is the json that is returned back:
[0]: {Id=1, Name="USA"}
[1]: {Id=2, Name="UK"}
[0]: {Id=1, Name="Alabama "}
[1]: {Id=2, Name="Florida"}
[2]: {Id=3, Name="London"}
In case of usage free jqGrid you can use a little simplified code
$(function () {
"use strict";
var countries = "usId:US;ukId:UK",
allStates = "alabamaId:Alabama;californiaId:California;floridaId:Florida;hawaiiId:Hawaii;londonId:London;oxfordId:Oxford",
// the next maps provide the states by ids to the countries
statesOfCountry = {
"": allStates,
usId: "alabamaId:Alabama;californiaId:California;floridaId:Florida;hawaiiId:Hawaii",
ukId: "londonId:London;oxfordId:Oxford"
},
mydata = [
{ id: "10", country: "usId", state: "alabamaId", name: "Louise Fletcher" },
{ id: "20", country: "usId", state: "floridaId", name: "Jim Morrison" },
{ id: "30", country: "ukId", state: "londonId", name: "Sherlock Holmes" },
{ id: "40", country: "ukId", state: "oxfordId", name: "Oscar Wilde" }
],
$grid = $("#list"),
changeStateSelect = function (countryId, countryElem) {
// build "state" options based on the selected "country" value
var $select, selectedValues,
$countryElem = $(countryElem),
isInSearchToolbar = $countryElem.parent().parent().parent().parent().hasClass("ui-search-table");
// populate the subset of countries
if (isInSearchToolbar) {
// searching toolbar
$select = $countryElem.closest("tr.ui-search-toolbar")
.find(">th.ui-th-column select#gs_list_state");
} else if ($countryElem.is(".FormElement")) {
// form editing
$select = $countryElem.closest("form.FormGrid")
.find("select#state.FormElement");
} else {
// inline editing
$select = $("select#" + $.jgrid.jqID($countryElem.closest("tr.jqgrow").attr("id")) + "_state");
}
if ($select.length > 0) {
selectedValues = $select.val();
if (isInSearchToolbar) {
$select.html("<option value=\"\">All</option>");
} else {
$select.empty();
}
$.jgrid.fillSelectOptions($select[0], statesOfCountry[countryId], ":", ";", false, selectedValues);
}
},
dataInitCountry = function (elem) {
setTimeout(function () {
$(elem).change();
}, 0);
},
dataEventsCountry = [
{ type: "change", fn: function (e) { changeStateSelect($(e.target).val(), e.target); } },
{ type: "keyup", fn: function (e) { $(e.target).trigger("change"); } }
],
cancelInlineEditingOfOtherRows = function (rowid) {
var $self = $(this), savedRows = $self.jqGrid("getGridParam", "savedRow");
if (savedRows.length > 0 && rowid !== savedRows[0].id) {
$self.jqGrid("restoreRow", savedRows[0].id);
}
};
$grid.jqGrid({
data: mydata,
datatype: "local",
colNames: [ "Name", "Country", "State" ],
colModel: [
{ name: "name", width: 180 },
{ name: "country", formatter: "select", stype: "select", edittype: "select",
searchoptions: {
noFilterText: "Any",
dataInit: dataInitCountry,
dataEvents: dataEventsCountry
},
editoptions: {
value: countries,
dataInit: dataInitCountry,
dataEvents: dataEventsCountry
}},
{ name: "state", formatter: "select", stype: "select", edittype: "select",
editoptions: { value: allStates }, searchoptions: { noFilterText: "Any" } }
],
cmTemplate: { width: 100, editable: true },
onSelectRow: cancelInlineEditingOfOtherRows,
ondblClickRow: function (rowid) {
cancelInlineEditingOfOtherRows.call(this, rowid);
$(this).jqGrid("editRow", rowid);
},
inlineEditing: {
keys: true
},
formEditing: {
onclickPgButtons: function (whichButton, $form, rowid) {
var $self = $(this), $row = $($self.jqGrid("getGridRowById", rowid)), countryId;
if (whichButton === "next") {
$row = $row.next();
} else if (whichButton === "prev") {
$row = $row.prev();
}
if ($row.length > 0) {
countryId = $self.jqGrid("getCell", $row.attr("id"), "country");
changeStateSelect(countryId, $form.find("#country")[0]);
}
},
closeOnEscape: true
},
searching: {
searchOnEnter: true,
defaultSearch: "cn"
},
navOptions: {
del: false,
search: false
},
iconSet: "fontAwesome",
sortname: "name",
sortorder: "desc",
viewrecords: true,
rownumbers: true,
pager: true,
pagerRightWidth: 85, // fix wrapping or right part of the pager
caption: "Demonstrate dependent selects (inline editing on double-click)"
})
.jqGrid("navGrid")
.jqGrid("filterToolbar");
});
see https://jsfiddle.net/OlegKi/svnL4Lsv/3/

On First load of jqgrid how to load page of specific record?

Using Jquery.Jqgrid v4.4.4
I have 10 pages in my State grid, i want to display the page which holds state name 'Tamilnadu' on first of the jqgrid loads. Not to bring the state on the first page, need to display that page on the first time.
EDIT: My Jqgrid code, here i have 'State' column contains 10+ pages , in one of the page 'Tamilnadu' state record is there. Please help me on how to load the grid with that page on first load.
// Setting up County Grid properties
$(function () {
$("#CountyGrid").jqGrid({
url: '/ControlTables/GetCountyResult',
datatype: "json",
contentType: "application/json; charset-utf-8",
mtype: 'Get',
colNames: ['CountyIdentifier', 'Active', 'State', 'County', 'County Number', AddNewBtn],
colModel: [
{
Key: true, name: 'CountyIdentifier', index: 'CountyIdentifier', width: 16, editable: false, sortable: true, align: "left", classes: "grid-col",
hidden: true, displayName: "CountyIdentifier"
},
{
name: 'ActiveFlag', index: 'ActiveFlag', width: 4, align: 'center', editable: true,
edittype: 'checkbox', editoptions: { value: "True:False", defaultValue: "True" }, formatter: "checkbox", displayName: "Active"
},
{
name: 'StateIdentifier', index: 'StateIdentifier', editable: true, formatter: 'select', sortable: true,
edittype: 'select', width: 19, align: "left", classes: "grid-col", editoptions: { style: "height:23px;" }, displayName: "State", valueField: "StateText",
},
{
name: 'CountyText', index: 'CountyText', width: 19, editable: true, sortable: true, align: "left", classes: "grid-col",
editoptions: { style: "height:23px;", maxlength: "48", dataInit: function (el) { $(el).css('text-transform', 'uppercase'); } }, displayName: "County"
},
{
name: 'CountyNumber', index: 'CountyNumber', width: 7, editable: true, sortable: true, align: "left", classes: "grid-col",
editoptions: { style: "height:23px;", maxlength: "5" }, displayName: "County Number"
},
{
name: "action", index: "action", sortable: false, editable: false, align: "center", width: "7", displayName: "Action"
},
],
// Call select row function
onSelectRow: function (id) {
if (onPagingLastSel) {
$('#CountyGrid').jqGrid('resetSelection', lastsel, true);
onPagingLastSel = false;
}
rowSelect(id);
},
onPaging: function () {
//Prompt to save pending changes when the user try to navigate Next/Previous/Front/Last page.
if (lastsel != null) {
$('#CountyGrid').jqGrid('saveRow', lastsel, {});
var editrowData = jQuery("#CountyGrid").getRowData(lastsel);
var editRow_ActiveFlag = editrowData['ActiveFlag']
var editRow_StateIdentifier = editrowData['StateIdentifier']
var editRow_CountyText = editrowData['CountyText']
var editRow_CountyNumber = editrowData['CountyNumber']
$('#CountyGrid').jqGrid('editRow', lastsel, {});
if ((lastsel_StateIdentifier != editRow_StateIdentifier && editRow_StateIdentifier != undefined)||
(lastsel_CountyText != editRow_CountyText && editRow_CountyText != undefined) ||
(lastsel_CountyNumber != editRow_CountyNumber && editRow_CountyNumber != undefined) ||
(lastsel_ActiveFlag != editRow_ActiveFlag && editRow_ActiveFlag != undefined)) {
DialogConfirmSave("GENL-002");
onPagingLastSel = true;
return 'stop';
}
else {
lastsel = null;
//enable New Button
$("#NewBtnId").removeClass('add-new-button-disable');
$("#NewBtnId").removeAttr("disabled");
}
}
},
// load all States into jqGrid dropdown
beforeProcessing: function (response) {
var $self = $(this),
options = response.colModelOptions, StateIdentifier;
if (options != null) {
for (StateIdentifier in options) {
if (options.hasOwnProperty(StateIdentifier)) {
$("#CountyGrid").jqGrid("setColProp", StateIdentifier, options[StateIdentifier]);
}
}
}
},
// Grid column header alignment to the left diable new button for general users
loadComplete: function () {
$("#CountyGrid").jqGrid("setLabel", "Active", "", { "text-align": "left" })
$("#CountyGrid").jqGrid("setLabel", "StateIdentifier", "", { "text-align": "left" })
$("#CountyGrid").jqGrid("setLabel", "CountyText", "", { "text-align": "left" })
$("#CountyGrid").jqGrid("setLabel", "CountyNumber", "", { "text-align": "left" })
},
pager: jQuery('#CountyPager'),
rowNum: jqGridRowCount,
rowList: GridRowList,
viewrecords: true,
emptyrecords: 'No records to display',
jsonReader: {
root: "rows",
page: "page",
total: "total",
records: "records",
repeatitems: false,
Id: "0"
},
multiselect: false,
autowidth: true,
height: 560,
hidegrid: false,
}).navGrid('#CountyPager', {
edit: false, add: false, del: false, search: false, refresh: false, reload: false, restoreAfterSelect: false
})
});
My Controller code:
public JsonResult GetCountyResult(string sidx, string sord, int page, int rows, bool getAllRecords = false)
{
objCountyViewModel = new CountyViewModel();
int totalRecords = 0;
if (Session["CountyList"] != null && Session["CountyList"] is List<CountyModel>)
{
objCountyViewModel.CountyModelList = (List<CountyModel>)Session["CountyList"];
if (objCountyViewModel.CountyModelList != null)
{
Session["CountyList"] = objCountyViewModel.SortCounty(sidx, sord);
totalRecords = objCountyViewModel.CountyModelList.Count();
}
}
var totalPages = (int)Math.Ceiling((float)totalRecords / (float)rows);
rows = getAllRecords ? totalRecords : rows;
var jsonData = new
{
colModelOptions = new
{
StateIdentifier = new
{
formatter = "select",
edittype = "select",
editoptions = new
{
value = objCountyViewModel.GetStateDropdownList()
}
}
},
total = totalPages,
page,
records = totalRecords,
rows = objCountyViewModel.GetCountyPageList(page, rows)
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}

jqgrid does not fire when the ENTER key gets pressed

I need to trap when the user presses ENTER in edit mode and this code works every time any other key gets pressed but not ENTER.
Any ideas why? maybe there is an automatic setting that needs to be set to false?
$(dispgrid).jqGrid({
url: als.common.getServerPath() + 'WorkorderAjax/GetDispositionFields',
datatype: 'local',
mtype: 'POST',
height: 292,
width: 480,
caption: 'Disposition Instructions',
hidegrid: false,
loadtext: 'Please wait,</br>loading disposition fields...',
colModel: [
{ name: 'Description', label: 'Description', sortable: false, width: 120, align: 'left' },
{ name: 'Fraction', label: 'Split', sortable: false, width: 40, align: 'center' },
{
name: 'Disposition', label: 'Disposition', sortable: false, align: 'left',
editable: true, edittype: 'select', classes: 'disposition_list'
},
{ name: 'PickList', label: 'PickList', sortable: false, hidden: true },
{
name: 'FreeDays', label: 'FreeDays', sortable: false, editable: true
},
{ name: 'MaxFreeDays', label: 'MaxFreeDays',hidden: true }
],
pgbuttons: false,
pginput: false,
rowNum: 999,
loadComplete: function () {
currentRowId = undefined;
prevRowId = undefined;
prevRowModified = false;
},
onSelectRow: function (rowId) {
if (prevRowId !== undefined) {
if (prevRowModified) {
//validate free days here
var selRowId = $(dispgrid).jqGrid('getGridParam', 'selrow');
var freedays = $("#" + prevRowId + "_FreeDays", dispgrid).val();
var maxfreedays = $(dispgrid).jqGrid('getCell', selRowId, 'MaxFreeDays');
if (parseInt(freedays) > parseInt(maxfreedays)) {
$(dispgrid).jqGrid('restoreRow', selRowId);
showErrorDialog("Free days can not be larger than " + maxfreedays);
$(dispgrid).resetSelection();
$(dispgrid).setSelection(prevRowId, false);
return true;
}
saveparameters = {
url: als.common.getServerPath() + 'WorkorderAjax/UpdateDispositionFields',
extraparam: {
folderno: wo,
fraction: prevRowId,
disposition: $('#' + prevRowId + '_Disposition', this).val(),
freedays: $('#' + prevRowId + '_FreeDays', this).val()
},
successfunc: function () {
$(this).trigger("reloadGrid");
prevRowModified = false;
$(this).restoreRow(prevRowId);
return true;
}
};
$(this).jqGrid('saveRow', prevRowId, saveparameters);
}
else {
$(this).restoreRow(prevRowId);
}
}
currentRowId = rowId;
var rowData = $(this).jqGrid('getRowData', currentRowId);
var unformatted = rowData.PickList;
var formatted = '';
var ar = unformatted.split(',');
for (var i = 0; i < ar.length; i++) {
formatted += ar[i] + ':' + ar[i]
+ (i < ar.length - 1 ? ';' : '');
}
$(this).setColProp('Disposition', { editoptions: { value: formatted } });
saveparameters = {
url: als.common.getServerPath() + 'WorkorderAjax/UpdateDispositionFields',
extraparam: {
folderno: wo,
fraction: currentRowId,
disposition: $('#' + currentRowId + '_Disposition', this).val()
},
successfunc: function () {
$(this).trigger("reloadGrid");
prevRowModified = false;
return true;
},
keys: true
};
$(this).editRow(currentRowId, saveparameters);
prevRowId = currentRowId;
}
}).closest('div.ui-jqgrid-view').children('div.ui-jqgrid-titlebar').css('text-align', 'center').
children('span.ui-jqgrid-title').css('float', 'none');
$(dispgrid).on('change', '', function () { prevRowModified = true; });
$(dispgrid).on('keydown', '', function (e) {
//the break point here gets hit every time unless the user presses ENTER key
if (e.keyCode == 13) {
}
});
keys:false in the saveparameters did the trick

Cancel the update in inline kendo grid delete the row

I am using two kendo inline grid parent and child. child grid contains the list of products,when user select the products(multiple selection) from child grid and clicked to save button,it's inserted into an parent grid.
Child grid:
var selectedIds = {};
var ctlGrid = $("#KendoWebDataGrid3");
ctlGrid.kendoGrid({
dataSource: {
data:data1,
schema: {
model: {
id: 'id',
fields: {
select: {
type: "string",
editable: false
},
Qty: {
editable: true,
type: "number",
validation: { min: 1, required: true }
},
Unit: {
editable: false,
type: "string"
},
StyleNumber: {
editable: false,
type: "string"
},
Description: {
editable: false,
type: "string"
}
}
}
},
pageSize: 5
},
editable: 'inline',
selectable: "multiple",
sortable: {
mode: 'single',
allowUnsort: false
},
pageable: true,
columns: [{
field: "select",
title: " ",
template: '<input type=\'checkbox\' />',
sortable: false,
width: 35},
{
title: 'Qty',
field: "Qty",
width:90},
{
field: 'Unit',
title: 'Unit',
width: 80},
{
field: 'StyleNumber',
title: 'Style Number',
},
{
field: 'Description',
width: 230},
{command: [<!---{text:"Select" ,class : "k-button",click: selectProduct},--->"edit" ], title: "Command", width: 100 }
],
dataBound: function() {
var grid = this;
//handle checkbox change
grid.table.find("tr").find("td:first input")
.change(function(e) {
var checkbox = $(this);
var selected = grid.table.find("tr").find("td:first input:checked").closest("tr");
grid.clearSelection();
//persist selection per page
var ids = selectedIds[grid.dataSource.page()] = [];
if (selected.length) {
grid.select(selected);
selected.each(function(idx, item) {
ids.push($(item).data("id"));
});
}
})
.end()
.mousedown(function(e) {
e.stopPropagation();
})
//select persisted rows
var selected = $();
var ids = selectedIds[grid.dataSource.page()] || [];
for (var idx = 0, length = ids.length; idx < length; idx++) {
selected = selected.add(grid.table.find("tr[data-id=" + ids[idx] + "]") );
}
selected
.find("td:first input")
.attr("checked", true)
.trigger("change");
}
});
var grid = ctlGrid.data("kendoGrid");
grid.thead.find("th:first")
.append($('<input class="selectAll" type="checkbox"/>'))
.delegate(".selectAll", "click", function() {
var checkbox = $(this);
grid.table.find("tr")
.find("td:first input")
.attr("checked", checkbox.is(":checked"))
.trigger("change");
});
save button clicked Event
function selectProduct()
{
//Selecting child Grid
var gview = $("#KendoWebDataGrid3").data("kendoGrid");
//Getting selected rows
var rows = gview.select();
//Selecting parent Grid
var parentdatasource=$("#grid11").data("kendoGrid").dataSource;
var parentData=parentdatasource.data();
//Iterate through all selected rows
rows.each(function (index, row)
{
var selectedItem = gview.dataItem(row);
var selItemJson={id: ''+selectedItem.id+'', Qty:''+selectedItem.Qty+'',Unit:''+selectedItem.Unit+'',StyleNumber:''+selectedItem.StyleNumber+'',Description:''+selectedItem.Description+''};
//parentdatasource.insert(selItemJson);
var productsGrid = $('#grid11').data('kendoGrid');
var dataSource = productsGrid.dataSource;
dataSource.add(selItemJson);
dataSource.sync();
});
closeWindow();
}
Parent Grid:
var data1=[];
$("#grid11").kendoGrid({
dataSource: {
data:data1,
schema: {
model: { id: "id" ,
fields: {
Qty: { validation: { required: true } },
Unit: { validation: { required: true } },
StyleNumber: { validation: { required: true } },
Description: { validation: { required: true } }
}
}
},
pageSize: 5
},
pageable: true,
height: 260,
sortable: true,
toolbar: [{name:"create",text:"Add"}],
editable: "inline",
columns: [
{field: "Qty"},
{field: "Unit"},
{field: "StyleNumber"},
{field: "Description"},
{ command: ["edit", "destroy"], title: " ", width: "172px" }]
});
$('#grid11').data().kendoGrid.bind("change", function(e) {
$('#grid11').data().kendoGrid.refresh();
});
$('#grid11').data().kendoGrid.bind('edit',function(e){
if(e.model.isNew()){
e.container.find('.k-grid-update').click(function(){
$('#grid11').data().kendoGrid.refresh();
}),
e.container.find('.k-grid-cancel').click(function(){
$('#grid11').data().kendoGrid.refresh();
})
}
})
Adding data into parent grid work nicely,no issue,but when i select the parent grid add new row to edit then trigger the cancel button row was deleted.
I am not able to figure out the problem.please help me.
I found the error, hope can help you.
If you did not config the dataSource: schema: model's "id" field, when click edit in another row before update or click cancel, it will delete the row.
var dataSource = new kendo.data.DataSource({
...
schema: {
model: {
id:"id", // Look here, if you did not config it, issue will happen
fields: {...
...}
}
}
...
})
I have the same issue, and I config cancel like :
...
cancel: function(e) {
this.refresh();
},
...
I don't think it's the best way, but it's working.
Hope another people can give us a better way.
after saving I call $('#grid').data('kendoGrid').dataSource.read();
that cancels the edit row and reads any changes.
Still doesn't seem to be fixed.
I'm addressing it with 'preventDefault()'. This may require explicit closing of window as a consequence.
cancel: function (e) {
// Not sure why this is needed but otherwise removes row...
e.preventDefault();
e.container.data("kendoWindow").close();
},
schema: {
model: { id: "StyleNumber" // "Any ID Field from the Fields list" ,
fields: {
Qty: { validation: { required: true } },
Unit: { validation: { required: true } },
StyleNumber: { validation: { required: true } },
Description: { validation: { required: true } }
}
}
}
This will solve your problem.

Resources