Jquery Grid row remains in the edited form saveRow event is called and another row is clicked - jquery-plugins

I have a grid that is loaded inside a jquery dialog. I have done row editing and row saving within onSelectRow event. When a row is edited and saved and then another row is clicked, previous row remains in the edited form. I am not able to save and remove the edited form.
Id of my table on which I want to load the grid is MultiCount.
And I have binded the grid inside a function bindShapesGrid(), below is the code.
I have hardcoded a XML String and used it as the data.
function bindShapesgrid() {
var xmlstring = "<root><rows><row><cell>Shortnamevalue</cell><cell>does not equal</cell><cell>and</cell><cell>sad</cell><cell></cell><cell></cell></row><row><cell></cell><cell></cell><cell></cell><cell></cell><cell></cell><cell></cell></row></rows></root>"
var lastsel2;
jQuery("#MultiCount").jqGrid({
datatype: 'xmlstring',
datastr: xmlstring,
colNames: ['ShortName', 'Operand 1', 'Value 1', 'AndOr', 'Operand 2', 'Value 2'],
colModel: [{ name: 'ShortName', index: 'ShortName', align: 'center', width: 80, editable: true, edittype: "select" },
{ name: 'Operand1', index: 'Operand1', align: 'center', width: 90, editable: true, edittype: "select", editoptions: { value: RetrievegridOperandList() } },
{ name: 'Value1', index: 'Value1', align: 'center', width: 40, editable: true },
{ name: 'AndOr', index: 'Refer', align: 'center', width: 80, editable: true, edittype: "select", editoptions: { value: "AND:And;OR:Or" } },
{ name: 'Operand2', index: 'Operand2', align: 'center', width: 80, edittype: "select", editable: true, editoptions: { value: RetrievegridOperandList() } },
{ name: 'Value2', index: 'Value2', align: 'center', width: 40, editable: true }],
root: 'rows',
row: 'row',
celledit: true,
sortname: 'ShortName',
sortorder: 'asc',
viewrecords: true,
gridview: true,
height: "100%",
rowNum: 10,
onSelectRow: function (id) {
if (id && id !== lastsel2) {
jQuery('#MultiCount').jqGrid('editRow', id, true);
jQuery("#MultiCount").jqGrid('saveRow', lastsel2, true);
lastsel2 = id;
}
}
});
}

Related

Options for selecting multiple rows and individual rows

I am using JQGrid and I want an option for multiple selection of rows. I used " multiselect: true," but it is not working. Yes I have got an column in the grid that have checkbox in each row but if I select top checkbox which is in header , it just selects first row from grid
Even single selection of row is not working properly. If checked at one checkbox, it selects and then if I check another box in the another row, it unchecks the first checked checkbox.
Here is my grid Code.
$(document).ready(function () {
$("#btnGetdetails").click(function () {
bindReports();
});
var bindReports = function () {
$('#list1').jqGrid('GridUnload');
$("#list1").jqGrid({
url: "GetNotesReportDetails",
postData: { startDate: $('#startDate').val(), endDate: $('#endDate').val(), ins_Type: $("#InsuranceType").val(), ass_Clincian: $("#ddlAssignedClician").val() },
datatype: "json",
mtype: "POST",
colNames: ["ID", "#", "First Name", "Last Name", "Date Of Birth", "Date of Visit", "Insurance Type", "Insurance ID","Clinician" ,"Procedure Code", "Fee Schedule"],
colModel: [
{ name: "ID", index: "ID", hidden: true, key: true },
{ name: "SNo", index: "SNo", width: 10, align: "left" },
{ name: "FirstName", index: "FirstName", width: 40, align: "left", sortable: true, formatter: 'showlink', formatoptions: { baseLinkUrl: 'javascript:', showAction: "Link('", addParam: "');" } },
{ name: "LastName", index: "LastName", width: 40, align: "left", sortable: true, formatter: 'showlink', formatoptions: { baseLinkUrl: 'javascript:', showAction: "Link('", addParam: "');" } },
{ name: "DateofBirth", index: "DateofBirth", width: 40, align: "left", formatter: 'date', sorttype: "date", sortable: true },
{ name: "DateofVisit", index: "DateofVisit", width: 40, align: "left", formatter: 'date', sorttype: "date", sortable: true },
{ name: "PageType", index: "PageType", width: 40, align: "left", sortable: true },
{ name: "InsuranceID", index: "InsuranceID", width: 50, align: "left", sortable: true },
{ name: "Clinician", index: "Clinician", width: 50, align: "left", sortable: true },
{ name: "ProcedureCode", index: "ProcedureCode", width: 50, align: "left", sortable: true },
{ name: "CodeFee", index: "CodeFee", width: 50, align: "left", sortable: true }],
// Grid total width and height
multiselect: true,
rowNum: 20,
rowList: [5, 10, 15, 20],
width: 900,
height: "100%",
// Paging
pager: $("#pager1"),
viewrecords: true,
// Default sorting
//sortname: "FirstName",
sortorder: "asc",
sortable: true,
loadonce: true,
hidegrid: false,
// Grid caption
caption: "Reports List"
}).navGrid("#pager1", { refresh: false, excel: 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
).jqGrid('navButtonAdd', '#pager1', {
caption: "Export to Excel",
buttonicon: "ui-icon-bookmark",
onClickButton: genGraph,
position: "last"
});
}
});
Probably you have problem in your data. You used key: true for the column ID. It means that jqGrid will assign the value of id attribute of every row (id of <tr> element) with the value from ID column. If you would have the same values in ID column instead of providing unique values you would have exact the same behavior like you described in your question. If jqGrid will need to select or unselect an row then it will search the row by id. It will find the first row with the id if one have more as one row with the id. So it will select/unselect the first row in the grid in many cases.

How to reload a jqGrid with new query string value

I load jqgrid with drop down values using onchange event.
But when i again choose some other value in drop down i need the jqgrid to show the corresponding values.
Here s how i load the jqgrid
function getGrid() {
var mOptometrist = $('#optOptometristList').val();// Drop down value
alert(mOptometrist);
//jQuery("#list").jqGrid().setGridParam({ url: 'Schedule.ashx?mOptometristId=' + mOptometrist + '' }).trigger("reloadGrid");
jQuery("#jQGridDemo").jqGrid({
url: 'Schedule.ashx?mOptometristId=' + mOptometrist + '',
datatype: "json",
colNames: ['Id', 'Day', 'Start Time', 'End Time', 'Interval', 'Session', "Patient", 'Slots', 'Room Number'],
colModel: [
{ name: 'SlNo', index: '_id', width: 20, stype: 'text', editable: true, editoptions: { disabled: true} },
{ name: 'DayOfWeek', index: 'Day', width: 150, stype: 'text', sortable: true, editable: true, edittype: "select", formatter: 'select', editoptions: { value: getAllSelectOptions()} },
{ name: 'StartTime', index: 'StartTime', width: 150, editable: true, formatter: 'date', formatoptions: { srcformat: 'u', newformat: 'H:i:s'} },
{ name: 'EndTime', index: 'EndTime', width: 60, editable: true, formatter: 'date', formatoptions: { srcformat: 'u', newformat: 'H:i:s'} },
{ name: 'Interval', index: 'Interval', width: 80, align: "right", editable: true },
{ name: 'Session', index: 'Session', width: 40, align: "right", editable: true },
{ name: 'PatientsPerSlot', index: 'Patient', width: 80, align: "right", editable: true },
{ name: 'Slots', index: 'Slots', width: 150, sortable: false, editable: true },
{ name: 'RoomID', index: 'RoomNumber', width: 100, sortable: false, editable: true }
],
rowNum: 10,
mtype: 'GET',
loadonce: false,
rowList: [10, 20, 30],
pager: '#jQGridDemoPager',
sortname: '_id',
viewrecords: true,
sortorder: 'desc',
caption: "List Employee Details",
editurl: 'Schedule.ashx?mOptometristId= ' + mOptometrist,
loadComplete: function () {
$("#jQGridDemo").setColProp('Day', { editoptions: { value: "1:Sunday;2:Monday;3:Tuesday"} });
}
});
You can use
url: "",
postData: {
mOptometristId: function () {
return $('#optOptometristList').val();
}
}
instead of
url: 'Schedule.ashx?mOptometristId=' + mOptometrist + ''
Inside of onchange event you need just call $("#jQGridDemo").trigger("reloadGrid");. See the answer for more details.

In the Paging footer, aren't the Page [1 ] of 0 supposed to say "Page [0 ] of 0" if no record is found?

I noticed if there's no records to be returned then shouldn't the Paging footer say "0 of 0" instead of "1 of 0"??
Also, shouldn't the Paging textbox be disabled as well.
This is the JSON response I sent back to jqGrid
{ "total":0, "page":0, "records":0, "rows":[] }
I'm using jqGrid version 4.5.0
Thanks...
P.S. Source Code below...
$('#'+jqgridSpreadsheetId).jqGrid({
url: '../websrvc/JqGrid.ashx',
datatype: 'json',
mtype: 'POST',
postData: { WhichJqgridTemplate: '<%=JqqridTools.Template.MyInventory%>', WhichAction: '<%=JqqridTools.Action.Display%>', WebpageQuickQuoteSalePrice: '<%=postQuickQuoteSalePrice%>' },
colNames: ['Id', 'Stock Number', 'VIN', 'Year', 'Make', 'Model', 'Trim', 'Mileage', 'Purchase Price', 'Stock Date', 'Repair Cost', 'Total Cost', 'Days In Inventory', 'Hidden-Inventory-Tracker-Location-Id', 'Inventory Tracker Location', 'Links'], //Display Text in Column Header...
colModel: [
//In this case, use "sorttype" property in "colModel" for it to work when "loadonce" is set to true...
//formatter doc --> "http://www.trirand.com/jqgridwiki/doku.php?id=wiki:predefined_formatter&s[]=cell&s[]=formatter"...
//formatter hyperlink --> Stackoverflow posting was said to use formatter's function declaration instead of formatter's "showlink" followed by "formatoptions"...
// --> (Old Link) - http://stackoverflow.com/questions/5010761/linking-from-a-column-value-in-jqgrid-to-a-new-page-using-get...
// --> (New Link) - http://stackoverflow.com/questions/14529358/jqgrid-need-hyperlink-need-to-capture-value-through-jquery/14537512#14537512...
// --> (New Link) - http://www.trirand.com/jqgridwiki/doku.php?id=wiki:custom_formatter...
// --> Reasons are --> 1) far simpiler to use formatter for reading/writing and 2) much quicker and better performance...
{ name: 'Id', index: 'Id', sorttype: 'int', width: 0, align: 'left', hidden: true, hidedlg: true }, //"hidedlg" is use to hide the hidden column in "Column Chooser"...
{ name: 'StockNumber', index: 'StockNumber', sorttype: 'text', width: 100, align: 'center', searchoptions: { sopt: ['eq', 'ne'] } },
{ name: 'Vin', index: 'Vin', sorttype: 'text', width: 140, align: 'center', searchoptions: { sopt: ['eq', 'ne'] } },
{ name: 'Year', index: 'Year', sorttype: 'int', width: 50, align: 'center', searchoptions: { sopt: ['eq', 'ne'] } },
{ name: 'Make', index: 'Make', sorttype: 'text', width: 80, align: 'center', searchoptions: { sopt: ['eq', 'ne'] } },
{ name: 'Model', index: 'Model', sorttype: 'text', width: 80, align: 'center', searchoptions: { sopt: ['eq', 'ne'] } },
{ name: 'Trim', index: 'Trim', sorttype: 'text', width: 100, align: 'center', searchoptions: { sopt: ['eq', 'ne'] } },
{ name: 'Mileage', index: 'Mileage', sorttype: 'int', width: 60, align: 'center', formatter: 'number', formatoptions: {decimalSeparator:'',thousandsSeparator:',',decimalPlaces:0,defaultValue:'0'} },
{ name: 'PurchasePrice', index: 'PurchasePrice', sorttype: 'currency', width: 80, align: 'center', formatter: 'currency', formatoptions: {decimalSeparator:'.',thousandsSeparator:',',decimalPlaces:2,defaultValue:'0.00',prefix:'$',suffix:''} },
{ name: 'StockDate', index: 'StockDate', sorttype: 'date', width: 90, align: 'center', formatter: 'date', formatoptions: { newformat: 'm/d/Y' } }, //"formatter" and "formatoptions" is required for date sorting to works properly...
{ name: 'RepairCost', index: 'RepairCost', sorttype: 'currency', width: 80, align: 'center', formatter: 'currency', formatoptions: { decimalSeparator: '.', thousandsSeparator: ',', decimalPlaces: 2, defaultValue: '0.00', prefix: '$', suffix: '' } },
{ name: 'TotalCost', index: 'TotalCost', sorttype: 'currency', width: 80, align: 'center', formatter: 'currency', formatoptions: { decimalSeparator: '.', thousandsSeparator: ',', decimalPlaces: 2, defaultValue: '0.00', prefix: '$', suffix: '' } },
{ name: 'DaysInInventory', index: 'DaysInInventory', sorttype: 'int', width: 65, align: 'center', formatter: 'number', formatoptions: { decimalSeparator: '', thousandsSeparator: ',', decimalPlaces: 0, defaultValue: '1' } },
{ name: 'InventoryTrackerLocationId', index: 'InventoryTrackerLocationId', sorttype: 'int', width: 0, align: 'left', hidden: true, hidedlg: true }, //"hidedlg" is use to hide the hidden column in "Column Chooser"...
{ name: 'InventoryTrackerLocation', index: 'InventoryTrackerLocation', sorttype: 'text', width: 120, align: 'center', searchoptions: { sopt: ['eq', 'ne'] } },
//Links is not present in json data from the website, so we customize it here...
{ name: 'Links', index: 'Links', sorttype: 'text', width: 80, align: 'center', formatter: function (cellValue, options, rowObject) { return "<span style='text-decoration:underline;cursor:pointer;'>Links</span>" }, search: false } //"search" is use to hide the field in search dialog...
],
beforeSelectRow: function (rowid, e) {
//http://stackoverflow.com/questions/16592547/how-to-have-custom-formatter-built-in-function-to-call-a-non-jqgrid-seperate-fun
//http://stackoverflow.com/questions/16592547/how-to-have-custom-formatter-built-in-function-to-call-a-non-jqgrid-seperate-fun
//http://stackoverflow.com/questions/14529358/jqgrid-need-hyperlink-need-to-capture-value-through-jquery/14537512#14537512
//http://stackoverflow.com/questions/13761222/how-to-fire-loadcomplete-after-new-row-is-added-in-jqgrid/13765086#13765086
//To attached javascript function to a clickable "Links" cell...
if (this.p.colModel[$.jgrid.getCellIndex($(e.target).closest("td")[0])].name === jqgridColumnNameLinks) {
jqgridPopupDialogLinkOptions(
$(this).getCell(rowid, jqgridColumnIdStockNumber), //Use $(this) instead for less overhead - It's what Oleg at jqGrid said....
$(this).getCell(rowid, jqgridColumnIdVin), //Use $(this) instead for less overhead - It's what Oleg at jqGrid said....
$(this).getCell(rowid, jqgridColumnIdInventoryTrackerLocationId) //Use $(this) instead for less overhead - It's what Oleg at jqGrid said....
);
return false;
}
},
pager: '#'+jqgridPagerId,
rowNum: 10,
rowList: [5, 10, 20, 50], //Drop-down selection in footer - To show how many rows per page...
//This "sortname"/"sortorder" tag must be specified for "getGridParam"'s 'datatype'/'sortname'/'sortorder' (column sorting) to work. (Some kind of jqGrid bug or feature which we need to hack to do a workaround with)...
<%if(postQuickQuoteSalePrice.Length > 0) {%>
sortname: 'TotalCost', sortorder: 'desc', //When coming from Quick-Quote webpage...
<%} else {%>
sortname: 'StockDate', sortorder: 'desc', //When coming from any webpages, especially the Product webpage...
<%}%>
viewrecords: true,
//gridview: true,
//imgpath: '',
caption: 'My Inventory',
width: 1022,
shrinkToFit: false,
height: 400,
sortable: true, /* This allows both 1) Moving columns sideway to other location fields and 2) for jqGrid Column Chooser Plugin / JQuery Multiselect Plugin to work... */
grouping: true, /* This allows row data to be group into row grouping... */
loadonce: true, //In this case, use "sorttype" property in "colModel" for it to work when "loadonce" is set to true...
emptyrecords: "No records to display",
loadError: function (xhr, st, err) {
alert("An error had occurred, please try again or notify webmaster of this error");
},
loadComplete: function () {
//http://stackoverflow.com/questions/16639339/how-do-i-get-a-column-to-be-sort-in-descending-order-upon-loading...
//=========================================================================================
// the code will be executed only at the first loading because jqGrid
// changes datatype to "local" after the first loading if we use
// loadonce option. We use setTimeout to allows jqGrid to make the first
// loading till the end and reload it AFTER that
//=========================================================================================
var $self = $(this); //This is needed as seperate objects to seperate itself from the binding jqGrid or $(this) objects for it to work. It wouldn't work if binded to itself...
if ($self.jqGrid('getGridParam', 'datatype') === 'json') { //This the value when loading webpage then the value of "datatype" option will become "local" afterward...
//$self.getGridParam({ sortname: 'TotalCost', sortorder: 'desc' }); //When coming from Quick-Quote webpage...
//$self.getGridParam({ sortname: 'StockDate', sortorder: 'desc' }); //When coming from any webpages, especially the Product webpage...
//$(this).triggerHandler('reloadGrid', [{ sortname: 'Year', sortorder: 'desc' }]);
setTimeout(function () {
//$('#' + jqgridSpreadsheetId).triggerHandler('reloadGrid', [{ sortname: 'Year', sortorder: 'desc' }]);
$self.triggerHandler("reloadGrid");
}, 50);
}
//=========================================================================================
jqgridSummarySpreadsheetDisplay();
}
});
Here's the snapshot using Firefox firebug. As you can see the json result is what you asked me to do, use "page":"0" instead of "page":0 . The jqGrid in the webpage showed 1 instead of 0.
I think the problem is in the line of jqGrid source code
ts.p.page = $.jgrid.getAccessor(data,dReader.page) || ts.p.page || 0;
You should change integer value of page to the string value:
{ "total":0, "page":"0", "records":0, "rows":[] }
or
{ "total":"0", "page":"0", "records":"0", "rows":[] }
which mostly exact corresponds to the format described in the documentation.
UPDATED: The demo reproduce your problem and another demo uses the fixed JSON data ("page":"0" instead of "page":0). How you can see the fix work.
UPDATED 2: I see now that the problem is in usage of loadonce: true. To fix the problem one can use
localReader: {
page: function (obj) {
return obj.page !== undefined ? obj.page : "0";
}
}
see one more demo.
UPDATED 3: I posted the full request which would fix the problems. The fix is already merged (see here) to the main code of jqGrid on the github.

JqGrid Custom search reload grid

Morning,
I am using jqGrid 4.4.1 - jQuery Grid. I have the next problem.
I have a custom search button, it permits filter data with some params
$('#BtnConsultar').click(function() {
parametros.NoSolicitud = $("#TxtNoSolicitud").val();
parametros.TipoSolicitud = $("#CbTiposSolicitud").val();
parametros.IdUsuario = $("#TxtIdUsuario").val();
parametros.Proveedor = $("#TxtProveedor").val();
parametros.FechaUltModificacionDesde = $("#TxtFechaUltModificacionDesde").val();
parametros.FechaUltModificacionHasta = $("#TxtFechaUltModificacionHasta").val();
parametros.FechaBorradoDesde = $("#TxtFechaBorradoDesde").val();
parametros.FechaBorradoHasta = $("#TxtFechaBorradoHasta").val();
jQuery('grid').jqGrid('clearGridData');
$("#GrdResultadoConsulta").jqGrid('setGridParam', { postData: { parametroJSON: JSON.stringify(parametros)} });
$('#GrdResultadoConsulta').trigger("reloadGrid", [{ current: true}]);
return true;
});
But if before filter data, i have a grid with 20 rows in group of 10 (2 pages) and the data that i want filter be in the second page the grid doesn´t show. I think is a sort problem because if i press colum sort the grid show the row.
Any one with some solution ?
This is my grid code
$("#GrdResultadoConsulta").jqGrid({
url: '<%= Url.Action("GridConsultaSolicitudeEliminadas")%>',
postData: { parametroJSON: JSON.stringify(parametros) },
datatype: 'json',
mtype: 'GET',
colNames: ['No.Solicitud', 'Tipo Solicitud', 'Usuario', 'Proveedor', 'Fecha Creación', 'Fecha Modificación', 'Fecha Borrado', 'Id Notificacion', 'SolicitudesEliminadasID'],
colModel: [
{ name: 'SolicitudID', index: 'SolicitudID', width: 75, align: 'left', sortable: true, resizable: false },
{ name: 'DescTipoSolicitud', index: 'TipoSolicitud', width: 75, align: 'center', sortable: true, resizable: false },
{ name: 'Usuario', index: 'IdUsuario', width: 200, align: 'left', sortable: true, resizable: false },
{ name: 'Proveedor', index: 'NumProv', width: 200, align: 'left', sortable: true, resizable: false },
{ name: 'FechaInicio', index: 'FechaInicio', width: 75, align: 'right', sortable: true, resizable: false },
{ name: 'FechaModificacion', index: 'FechaModificacion', width: 75, align: 'right', sortable: true, resizable: false },
{ name: 'FechaBorrado', index: 'FechaBorrado', width: 75, align: 'right', sortable: true, resizable: false },
{ name: 'IdNotificacion', width: 75, align: 'right', sortable: false, resizable: false },
{ name: 'SolicitudesEliminadasID', hidden: true }
],
pager: $('#GrdResultadoConsultaPager'),
rowNum: 10,
sortname: 'SolicitudID',
sortorder: 'asc',
autowidth: true,
height: '250px',
viewrecords: true,
caption: 'Resultado de consulta solicitudes eliminadas',
loadtext: "Cargando información ...",
hidegrid: false,
loadComplete: function() { },
onSelectRow: function(id) { }
}).navGrid('#GrdResultadoConsultaPager', { edit: false, add: false, search: false, del: false });
Thanks..
PD: Excuse for me english
I found my error.
The error wasn't in the grid, was in the stored procedure.
Solution: Moving the filters to CTE instruction and not in the final query result.
Regards

jqGrid formatCell event doesn't fire

For some reason (unknown to me) the event 'formatCell' doesn't fire (no alert message shown). see code below:
$("#jqgrid").jqGrid({
datatype: "json",
colNames: ['CurrecncyID', 'Currency', 'Value', 'Calculated', 'Value', '%', 'Calculated'],
colModel: [
{ name: 'CurrecncyID', index: 'CurrecncyID', hidden: true, width: 40 },
{ name: 'CurrencyName', index: 'CurrencyName', width: 150 },
{ name: 'FullPrice', index: 'FullPrice', width: 100, editrules: { custom: true, custom_func: priceCheck }, editable: true, align: 'right', formatter: priceFormatter },
{ name: 'CalcFullPrice', index: 'CalcFullPrice', width: 100, align: 'right', formatter: priceFormatter },
{ name: 'ActualPrice', index: 'ActualPrice', width: 100, editrules: { custom: true, custom_func: priceCheck }, editable: true, align: 'right', formatter: priceFormatter },
{ name: 'Precent', index: 'Precent', width: 100, align: 'right', formatter: 'integer', formatoptions: { prefix: "% "} },
{ name: 'CalcActualPrice', index: 'CalcActualPrice', width: 100, align: 'right', formatter: priceFormatter },
],
onSelectRow: function (id) {
if (id && id !== lastsel) {
jQuery('#jqgrid').restoreRow(lastsel);
jQuery('#jqgrid').editRow(id, true);
lastsel = id;
}
},
formatCell: function (rowid, cellname, value, iRow, iCol) {
alert("before edit");
},
jsonReader: {
repeatitems: false
},
rowNum: 20,
rowList: [10, 20, 30],
pager: '#jqpager',
sortname: 'CurrecncyID',
viewrecords: true,
sortorder: "desc",
caption: "Prices List",
autowidth: true,
height: "100%",
loadtext: "Loading...",
editurl: "/handlers/myurl.ashx"
});`
There are three main editing modes used in jqGrid. The formatCell event is a part of the cell editing mode. It will be not fire in case of usage of editRow and restoreRow are the part of the inline editing mode. Probably you need use custom editable element in case of the usage of the inline editing mode.

Resources