Cancel edit event in jqGrid inline edit - jqgrid

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

The easiest way to invoke the "cancel edit" button would be executing the code
$("#CommentsData_ilcancel").click(); // trigger click event on Cancel button
where CommentsData is the id of the grid.

Related

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

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

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

How to retrieve a text value in a kendo drop down list within a kendo grid cell but still pass the ID in CRUD

I'm having a problem finding a solution related to the Kendo Grid.
I am rendering a kendo dropdown list within a cell of a Kendo Grid. It appears to look fine and all, until the user focuses off or tabs off of the dropdown within the cell. The red hash shows that a change was made, but it's showing the data-value-field of the kendo DDL and not the text. Ok, I realize I can just use the same field from the DS in the dataTextField as I'm using in the dataValueField, but that won't work for me...because when I'm calling create or update, I need to be able to pass the primary key or ID of that selected item back into my web api controller.
Here is the grids DS
function loadContactGrid(vendorID) {
var contactsReadURL = null;
contactsReadURL = "/contacts/getcontacts/" + parseInt(vendorID);
contactGridDS = new kendo.data.DataSource({
transport: {
read: {
url: contactsReadURL,
type: 'GET',
contentType: "application/json; charset=utf-8",
},
update: {
url: "/contacts/UpdateContacts/",
type: 'PUT',
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function(xhRequest, ErrorText, thrownError) {
alert('ERROR!!!\n' + ' xhRequest: ' + xhRequest + '\n' + ' ErrorText: ' + ErrorText + '\n' + ' thrownError: ' + thrownError + '\n');
},
complete: function(e) {
$("#contactGrid").data("kendoGrid").dataSource.read();
}
},
destroy: {
url: "/contacts/DeleteContact/",
contentType: "application/json; charset=utf-8",
dataType: "json",
type: "DELETE"
},
create: {
url: "/contacts/InsertContact/",
contentType: "application/json; charset=utf-8",
type: 'POST',
dataType: "json",
success: function(results) {
alert('Contacts successfully saved!');
},
error: function(xhRequest, ErrorText, thrownError) {
alert('ERROR!!!\n' + ' xhRequest: ' + xhRequest + '\n' + ' ErrorText: ' + ErrorText + '\n' + ' thrownError: ' + thrownError + '\n');
},
complete: function(e) {
$("#contactGrid").data("kendoGrid").dataSource.read();
}
},
parameterMap: function(options, operation) {
if (operation !== "read" && options) {
return JSON.stringify(options.models);
}
if (operation == "create") {
// send the created data items as the "models" service parameter encoded in JSON
return { models: kendo.stringify(data.models) };
}
}
},
batch: true,
scrollable: false,
pageSize: 8,
change: function(e) {
if (e.action == "itemchange" && e.field == "email") {
var model = e.items[0];
if (isEmailValid($('input[name=email]').val()) == false) {
e.items[0].receivereport = false;
}
}
if (e.action == "itemchange" && e.field == "contacttype") {
var model = e.items[0];
//setTimeout(function () {
//$('.k-dirty-cell').focusout(function() {
//alert($(this).text(textOverrideContactType(e.items[0].contacttype)));
//});
//textOverrideContactType(e.items[0].contacttype);
//}, 1000); attempting to change text in cell here failed
}
if (e.action === "remove") {
this.sync();
}
},
schema: {
model: {
id: 'contactid',
fields: {
roletyp_seq: { editable: false, nullable: false, required: true, type: 'string' },
contacttype: { editable: true, nullable: false, required: true, type: 'number' },
roletyp_pk: { editable: false, nullable: false, required: true, type: 'number' },
contactid: { editable: false, nullable: false, required: true, type: 'number' },
vendorid: { editable: false, nullable: false, required: true, type: 'number' },
prevrole_pk: {
editable: false,
nullable: true,
required: true,
type: "number",
}
}
}
},
});
And my grid
$("#contactGrid").kendoGrid({
dataSource: contactGridDS,
navigatable: true,
dataBound: mapContactTypes,
editable: true,
//editable: "inline",
//editable: "popup",
edit: function (input) {
if ($('input[name=receivereport]').is(':focus')) {
//detect if email is valid
//get input immediately before this one
if (isEmailValid($('input[name=receivereport]').parent().prev().text()) == false) {
// disable check box
// alert("invalid");
$('input[name=receivereport]').attr('disabled', 'true');
$('input[name=receivereport]').prop('checked', false);
} else {
// enable check box
// alert("valid");
$('input[name=receivereport]').removeAttr('disabled');
$('input[name=receivereport]').prop('checked', false);
}
}
//when user clicks into or out of a field, if the name in the respective row name is blank, alert the user
var grid = this;
var fieldName = grid.columns[input.container.index()].field;
if (isNameInContactGridPopulated(fieldName) == false) {
alert("You can't leave out a contact name in the row you are editing.");
//disable save button
$('.k-grid-save-changes').addClass('k-state-disabled');
$('.k-grid-save-changes').hide();
} else {
//do nothing
$('.k-grid-save-changes').removeClass('k-state-disabled');
$('.k-grid-save-changes').show();
}
if ($('input[name=contactname]').is(":focus") == true) {
//disable save button
if ($('input[name=contactname]').val() == '') {
$('.k-grid-save-changes').addClass('k-state-disabled');
$('.k-grid-save-changes').hide();
}
}
$('input[name=contactname]').keyup(function() {
if ($(this).val() == '') {
$('.k-grid-save-changes').addClass('k-state-disabled');
$('.k-grid-save-changes').hide();
}
});
$('input[name=contactname]').focusout(function () {
if ($(this).val() != '') {
$('.k-grid-save-changes').removeClass('k-state-disabled');
$('.k-grid-save-changes').show();
}
});
},
toolbar: ["save", "cancel"],
pageable: true,
columns: [
{ field: 'roletyp_seq', title: 'RT Seq.', hidden: true, attributes: { 'class': 'contactCell_roletyp_seq' } },
{ field: 'contacttype', title: 'Contact Type', hidden: false, attributes: { 'class': 'contactCell_contacttype' }, editor: loadContactTypeEditor, width: "200px", template: "#=textOverrideContactType(1)#" },
//{ field: 'contacttype', title: 'Contact Type', hidden: false, attributes: { 'class': 'contactCell_contacttype' }, editor: loadContactTypeEditor, width: "200px", template: "#=textOverrideContactType(contacttype)#" },
//{ field: 'contacttype', title: 'Contact Type', hidden: false, attributes: { 'class': 'contactCell_contacttype' }, editor: loadContactTypeEditor, width: "200px" },
{ field: 'prevrole_pk', title: 'prev role ID', hidden: true, attributes: { 'class': 'contactCell_prevrole_pk' } },
{ field: 'roletyp_pk', title: 'Role Type ID', hidden: true, attributes: { 'class': 'contactCell_roletyp_pk' } },
{ field: 'contactid', title: 'Contact ID', hidden: true, attributes: { 'class': 'contactCell_contactid' } },
{ field: 'vendorid', title: 'Vendor ID', hidden: true, attributes: { "class": 'contactCell_vendorid' } },
{ field: 'contactname', title: 'Name', hidden: false, attributes: { "class": 'contactCell_contactname' } },
{ field: 'workphone', title: 'Phone', hidden: false, attributes: { "class": 'contactCell_phone' } },
{ field: 'mobilephone', title: 'Cell', hidden: false, attributes: { "class": 'contactCell_mobilephone' } },
{ field: 'title', title: 'Title', hidden: false, attributes: { "class": 'contactCell_title' } },
{ field: 'email', title: 'Email', hidden: false, attributes: { "class": 'contactCell_email' } },
{ field: 'receivereport', title: 'Receive Reports?', hidden: false, attributes: { "class": 'contactCell_receivereport' }, template: '<input type="checkbox" #= receivereport ? "checked=checked" : "" # value="" disabled="disabled" ></input>' },
{ command: "destroy", title: " ", width: "100px" }
],
sortable: {
mode: 'single',
allowUnsort: false
}
});
Then, I have two functions below. 1 is the custom editor and the other is an attempt I considered to override the text displayed in the kendo ddl.
function loadContactTypeEditor(container, options) {
var contactTypeDS = new kendo.data.DataSource({
dataType: "json",
type: "GET",
transport: {
read: "/contacts/GetAllContactTypes/"
}
});
contactTypeDS.read();
$('<input class="contactTypeDropDown" required data-text-field="roletyp_dsc" data-value-field="roletyp_pk" data-bind="value:' + options.field + '"/>').appendTo(container).kendoDropDownList({
dataTextField: "roletyp_dsc",
dataValueField: "roletyp_pk",
autoBind: false,
select: function (e) {
//if (e.sender.text() != '') {
// $('#contactGrid_active_cell').html(e.sender.text());
//}
//if (e.sender.text() != '') {
// setTimeout(function() {
// $('.contactCell_contacttype').text(e.sender.text());
// }, 1000);
//}
//options.model[options.field] = e.sender.text();
},
//dataBound: function(){
// options.model[options.field] = e.sender.text();
//},
dataSource: contactTypeDS
});
}
function textOverrideContactType(roleId) {
//need to find a match on the passed in role/contact type ID and return it's match to "mask/overwrite" the text that's there after a user selects an item in the dropdown
$.ajax({
dataType: 'json',
type: 'GET',
url: "/contacts/GetAllContactTypes/",
contentType: 'application/json; charset=utf-8',
success: function (data) {
$.each(data, function (key, val) {
if (roleId == key) {
return val;
}
});
},
failure: function (error) {
alert("Error loading contact types.");
}
});
}
To summarize: I tried a few things with no avail. What is happening, is, the DDL renders just fine, and even when the user doesn't move off of that DDL, the proper "label" shows, but when that control loses focus, it shows the data-value-field. I can't have that, I need to be able to show the data-text-field. That's why I wrote that textoverride method. But I'm trying to call it within the grid, fields's template: and it's not working. It says it doesn't recognize that function. I don't get it; it's clearly declared. What am I supposed to pass in as the parameter, it's not exactly like the demo here...a bit different, as I'm populating the DDL with another remote data source.
http://demos.telerik.com/kendo-ui/grid/editing-custom
Here's the other thing; I need that data-value-field, ID, to persist and be passed into my web api controller when it gets called. Right now, as it stands, I'm only able to get the "text" to show in the controller and not the "ID." That ID will not be available to me in the read method. The stored procs that the CRUD is hitting is completely different. My stored proc for insert and update needs to get that contacttype ID as the number.
Thanks in advance. I'm sure I'm close...
From the provided information it seems that you need to make the column ForegnKey by setting the "values" option of the column. Please check the example below:
[demo] Grid: ForeignKey column
[documentation] Grid API: columns.values option
I actually ended up using another means to do this. The above still seems illusive to me. I ended up changing the values of a key in another row, that was already available, to get passed back into the controller. I tried the answers provided with no avail. Sorry!

Retain filter text in filter toolbar on grid reload

I'm using jqgrid in which i'm trying to retain the filter text after the grid reload.
I have cell update functionality,
//Code:
$.ajax({
url: '#Url.Action("UpdateComments", "Home")',
datatype: 'json',
data: { 'resultData': filterResult, 'action': postdata.oper },
type: 'POST',
success: OnCompleteComments,
error: function (xhr, status, error) {
if (xhr.statusText == "Session TimeOut/UnAuthorized") {
alert(xhr.statusText);
window.location.href = '#Url.Action("LogOut", "Account")';
}
else
alert(xhr.responseText);
}
});
//After update Load the grid.
function OnCompleteComments(result) {
myfilter = $('#TransactionsGrid').jqGrid("getGridParam", "postData").filters;
Loadgrid($('#TransactionsGrid').getGridParam('page'));
}
After the successful udpate of the cell i'm reloading the grid for the cell to reflect the udpated values. In the OnComplete i'm getting the filter assigned to a golbally declared variable(myfilter).
//Grid:
datatype: 'local',
hoverrows: false,
colNames: colHeader,
colModel: colname,
localReader: { id: 'TransactionId' },
rowNum: 10,
hidegrid: false,
rownumbers: true,
pager: '#TransactionsGridPager',
viewrecords: true,
caption: "Transaction Details",
height: 'auto',
scrollOffset: 0,
page: PageNumber,
gridview: true,
shrinkToFit: true,
autoencode: true,
ignoreCase: true,
mySelection: {},
onInitGrid: function () {
// get reference to parameters
var p = $(this).jqGrid("getGridParam");
// set data parameter
p.data = gridData.BuildTransactionsDataTable;
},
In grid reload(ajax function is called), once the grid is loaded i'm re assigning the filter. In this place i'm getting the filtered results in the grid exactly bu the text which i used to filter the results is not in the filter toolbar. Its empty.
GridReload(Retain filter):
jQuery("#TransactionsGrid").jqGrid({
});
if (myfilter) {
var searchFiler = JSON.parse(myfilter).rules[0].data, grid = $("#TransactionsGrid"), f;
if (searchFiler.length === 0) {
grid[0].p.search = false;
$.extend(grid[0].p.postData, { filters: "" });
}
f = { groupOp: "OR", rules: [] };
f.rules.push({ field: JSON.parse(myfilter).rules[0].field, op: "cn", data: searchFiler });
grid[0].p.search = true;
$.extend(grid[0].p.postData, { filters: JSON.stringify(f) });
grid.trigger("reloadGrid", [{ page: 1, current: true }]);
}
Now i need the filtered text to be retained in the filter toolbar. how can i achieve this?

how to use jqgrid extraParam parameter of saveRow

where in one cell edittype is select with key value pair like below.
colModel: [
{name: 'Code', index: 'Code', width: '16%', editable: true, sortable: true },
{ name: 'ABC', index: 'ABC', width: '16%', editable: true, edittype: "select", editoptions: { value: "FE:FedEx;TN:TNT"} },
{ name: 'Emailid', index: 'Emailid', width: '16%', editable: true, sortable: true },
],
Now while adding new row if i selected the FedEx for ABC column it will send the FE to EditURL Link not FedEX so i want to send the FEDEX using extraParam to EditURL.
So please anyone let me know how to implement it.
For this my code is below
UPDATED CODE
var grid = jQuery("#list5").jqGrid({
url: '/home1/GetUserData',
datatype: "json",
mtype: "POST",
colNames: ['Code', 'LoginID', 'Emailid'],
colModel: [
{name: 'Code', index: 'Code', width: '16%', editable: true, sortable: true },
{ name: 'LoginID', index: 'LoginID', width: '16%', editable: true, sortable: true },
{ name: 'Emailid', index: 'Emailid', width: '16%', editable: true, edittype: "select", editoptions: { value: "FE:FedEx;TN:TNT"} },
],
rowNum: 10,
autowidth: true,
height: '100%',
rowList: 10,
pager: $("#pager2"),
editurl: "/home1/EditUserData",
onSelectRow: function (id) {
if (id && id !== lastsel2) {
if (id == "new_row") {
grid.setGridParam({ editurl: "/home1/InsertUserData" });
}
else {
grid.setGridParam({ editurl: "/home1/EditUserData" });
}
jQuery('#list5').restoreRow(lastsel2);
jQuery('#list5').jqGrid('editRow', id, true, pickdates);
$("#list5_ilsave").addClass("ui-state-disabled");
$("#list5_ilcancel").addClass("ui-state-disabled");
$("#list5_iladd").removeClass("ui-state-disabled");
$("#list5_iledit").removeClass("ui-state-disabled");
lastsel2 = id;
}
},
caption: "Simple data manipulation"
});
jQuery("#list5").jqGrid('navGrid', '#pager2', { edit: false, add: false, del: true, search: false, refresh: false }, {}, {}, { url: '/home1/DeleteUserData' });
jQuery('#list5').jqGrid('inlineNav', '#pager2', { edit: true, add: true, editParams: {extraparam: XYZ()}});
});
function XYZ()
{
// from here i want to return the text of combo of selected row.
}
Update code of Oleg
var grid = jQuery("#list5"),
editingRowId,
myEditParam = {
keys: true,
oneditfunc: function (id) {
editingRowId = id;
},
afterrestorefunc: function (id) {
editingRowId = undefined;
},
extraparam:
// we get the text of selected option from the column
// 'Emailid' and include the data as additional
// parameter 'EmailidText'
// EmailidText: function () {
// return $("#" + editingRowId + "_Emailid>option:selected").text();
//}
// **my changes here bind ABC Function which return key , value pair of object** IS THIS POSSIBLE
function () {
ABC();
}
};
grid.jqGrid({
url: '/home1/GetUserData',
datatype: "json",
...
onSelectRow: function (id) {
var $this = $(this), gridIdSelector = '#' + $.jgrid.jqID(this.id);
$this.jqGrid('setGridParam', {
editurl: (id === "new_row" ?
"/home1/InsertUserData" :
"/home1/EditUserData")
});
if (editingRowId !== id) {
$(gridIdSelector + "_iledit").click();
}
}
});
$grid.jqGrid('navGrid', '#pager',
{ edit: false, add: false, search: false, refresh: false},
{}, {}, { url: '/home1/DeleteUserData' });
// inlineNav has restoreAfterSelect: true per default so we don't need to call
// restoreRow explicitly
$grid.jqGrid('inlineNav', '#pager',
{ edit: true, add: true, editParams: myEditParam,
addParams: {addRowParams: myEditParam } });
The code could be about the following
var grid = jQuery("#list5"),
editingRowId,
myEditParam = {
keys: true,
oneditfunc: function (id) {
editingRowId = id;
},
afterrestorefunc: function (id) {
editingRowId = undefined;
},
extraparam: {
// we get the text of selected option from the column
// 'Emailid' and include the data as additional
// parameter 'EmailidText'
EmailidText: function () {
return $("#" + editingRowId + "_Emailid>option:selected").text();
}
}
};
grid.jqGrid({
url: '/home1/GetUserData',
datatype: "json",
...
onSelectRow: function (id) {
var $this = $(this), gridIdSelector = '#' + $.jgrid.jqID(this.id);
$this.jqGrid('setGridParam', {
editurl: (id === "new_row" ?
"/home1/InsertUserData" :
"/home1/EditUserData")
});
if (editingRowId !== id) {
$(gridIdSelector + "_iledit").click();
}
}
});
$grid.jqGrid('navGrid', '#pager',
{ edit: false, add: false, search: false, refresh: false},
{}, {}, { url: '/home1/DeleteUserData' });
// inlineNav has restoreAfterSelect: true per default so we don't need to call
// restoreRow explicitly
$grid.jqGrid('inlineNav', '#pager',
{ edit: true, add: true, editParams: myEditParam,
addParams: {addRowParams: myEditParam } });

Resources