jqgrid inline searching - asp.net-mvc-3

I have a jqgrid that I am performing an inline edit on. I am using the textarea instead of text. How do I submit the data once I'm done editing the cell. "Enter" works on text and obviously doesn't on textarea since it creates a new line.
This is a snippet from my code
grid4 = $('#CaseNotes').jqGrid({
...
{ name: 'Note', index: 'Note', width: 650, align: 'left', sortable: false,
editable: true, edittype: 'textarea', editoptions: { rows: '5', cols: '100' }
},
...
onSelectRow: function (id) {
if (id && id != lastsel) {
grid4.restoreRow(lastsel);
lastsel = id;
}
grid4.jqGrid('editRow', id, true, '', '', '', '', reload);
},
editurl: '#Url.Action("EditCaseNote", "CaseNote")',
...
});
//function to reload the grid
function reload(id, result) {
grid4.setGridParam(
{
url: '#Url.Action("DisplayCaseNotesGrid", "CaseInfo")',
datatype: 'json'
}
).trigger('reloadGrid');
}

If I understand you correct you mean "inline editing" instead of "inline searching". Because you can't use Enter key you have to include some additional button in the Navigator toolbar which call saveRow method. You can either add the corresponding row manually with respect of navButtonAdd or use inlineNav method.

Thanks to Oleg's advise I was able to solve this. Here is my code incase anyone runs into a similar problem. I removed my refresh function since I no longer needed it.
grid4 = $('#CaseNotes').jqGrid({
...
{ name: 'Note', index: 'Note', width: 650, align: 'left', sortable: false,
editable: true, edittype: 'textarea', editoptions: { rows: '5', cols: '100' }
},
...
onSelectRow: function (id) {
if (id && id != lastsel) {
grid4.restoreRow(lastsel);
lastsel = id;
}
grid4.jqGrid('editRow', id, { keys: true, afterrestorefunc: reload });
},
...
});
//Adds the button to the pager
grid4.jqGrid('navButtonAdd', '#casenotes_pager', {
caption: 'Save Case Note',
buttonicon: 'none',
onClickButton: function () {
//calls the saveRow function
grid4.jqGrid('saveRow', lastsel,
{
url: '#Url.Action("EditCaseNote", "CaseNote")'
}
);
//refreshes the grid
grid4.setGridParam(
{
url: '#Url.Action("DisplayCaseNotesGrid", "CaseInfo")',
datatype: 'json'
}
).trigger('reloadGrid');
}
});

Related

Sometimes jqgrid getChangedCell not return checkbox changed

when I insert/update table data. i use getChangedCell function for making input data before call API. like this.
let inputData = _$myTable.getChangedCells('all');
$.ajax({
type: "POST",
url: "/api/services/InsertData",
dataType: "json",
data: inputData
})
Please check sample image.
First I check checkbox. after then click save button.
At this moment, generally _$myTable.getChangedCells('all') return the correct value.
But, sometimes _$myTable.getChangedCells('all') return []
Table options are :
_$myTable.jqGrid({
mtype: "GET",
datatype: "local",
autowidth: true,
shrinkToFit: false,
cellEdit: true,
colModel: [
{
name: "id",
key: true,
hidden: true
},
...
],
onSelectRow: function (id) {
if (id && id !== optionlastsel) {
_$myTable.jqGrid('restoreRow', optionlastsel);
_$myTable.jqGrid('editRow', id, true);
optionlastsel = id;
}
},
afterEditCell: function (rowid, cellname, value, iRow, iCol) {
var checkboxNameSet = _.pluck(_.where(_$myTable.jqGrid("getGridParam").colModel, { edittype: 'checkbox' }), 'name');
if (checkboxNameSet.includes(cellname)) {
$('#' + rowid + '').addClass("edited");
}
}
})
Checkbox options are:
{
label: 'IsActive',
name: "isActive",
editable: true,
edittype: 'checkbox',
editoptions: { value: "true:false" },
editrules: { required: true },
formatter: "checkbox",
formatoptions: { disabled: false },
align: "center"
}
In addition, all the time, the network was fine.
Are there any options I missed or mistake?
Thank you for reading.

JqGrid not always passing hidden parameters

When I'm trying to save all rows from jqGrid table, hidden parameters are not always passed to controller. For example when I have 20 rows to save, 3 are without hidden parameters and the rest 17 are ok. I have 4.8.0 version of jqGrid. My question is if it is something wrong in my code or just some error in jqGrid
$.each($(gridObject.TableId).jqGrid('getDataIDs'), function (i, val) {
$(gridObject.TableId).jqGrid('editRow', val, true);
$(gridObject.TableId).saveRow(val, undefined, gridObject.ControllerAddress + 'Edit', undefined);
});
Wrong passed parameters
Correct passed parameters
Table definition:
$(gridObject.TableId).jqGrid({
url: gridObject.ControllerAddress + 'Get',
postData:
{
forSessionId: gridObject.PostData.ForSessionId,
pepper: Math.random()
},
colNames: ['Participant',
'Attended <input type="checkbox" id="allAttended" />',
'Passed <input type="checkbox" id="allPassed" />',
'Id', 'UserId', 'SessionId'],
colModel: [
// displayed always
{ name: 'ParticipantName' },
{
name: 'Attended', sortable: false, edittype: 'checkbox', formatter: 'checkbox', formatoptions: { disabled: false },editable: true,
editoptions: {
value: GridsDictionaries.Checkbox.Default.value,
dataEvents: [{
type: 'change', fn: function (e) {
if ($(this).prop('checked')==false) {
var passedCheckbox = $(this).closest('tr').find('td[aria-describedby=participations_table_Passed] input[type=checkbox]');
$(passedCheckbox).removeProp('checked');
}
}
}]
}
},
{
name: 'Passed', sortable: false, edittype: 'checkbox', formatter: 'checkbox', formatoptions: { disabled: false }, editable: true,
editoptions: {
value: GridsDictionaries.Checkbox.Default.value,
dataEvents: [{
type: 'change', fn: function (e) {
if ($(this).prop('checked')) {
var attendedCheckbox = $(this).closest('tr').find('td[aria-describedby=participations_table_Attended] input[type=checkbox]');
$(attendedCheckbox).prop('checked', true);
}
}
}]
}
},
// hidden
{ name: 'Id', hidden: true, key: true },
{ name: 'ParticipantId', hidden: true, editable: true },
{ name: 'SessionId', hidden: true, editable: true },
],
autowidth: true,
pager: "",
caption: "List of participants",
//ondblClickRow: gridObject.ToggleEdition, onPaging: gridObject.OnPaging,
loadComplete: function () {
$.each($(gridObject.TableId).jqGrid('getDataIDs'), function (i, val) {
$(gridObject.TableId).jqGrid('editRow', val, true);
$(gridObject.TableId + ' tr#' + val).unbind('keydown');
});
},
});
This is not a error in the code, but feature. As of the creation of jqGrid the hidden fields are not editable and its values are not posted a to the server (local data).
I highly recommend you to discover the documentation of Guriddo jqGrid.
In the link above is explained how to edit these fields.

JQGrid with Bootstrap Multiselect and Custom Save

I have 2 requirements I need to solve for. I'm using a JQGrid on an aspx page with other form controls. Saving the main form generates a database id that is populated in a hidden field. If the hidden field is empty, I don't want to save the grid record because I need the db id first. If the hidden field has a value, I want to save the row with a editurl.
The second part is related to a Bootstrap multiselect in one of the grid columns (I need the filtering capability). When a user selects a value from the multiselect I'd like to populate the PERNR column with the value selected. I can't use the onchange event for the multiselect since if the user doesn't change from the first option obviously it won't trigger the event.
How can I solve these 2 issues?
var roleDdlItems = $.parseJSON($("input[id$='hdfRoleDdlItems']").val());
$("#grdParticipants").jqGrid({
jsonReader: {
repeatitems: false,
root: 'Table',
page: function (obj) { return 1; },
total: function (obj) { return 2; },
records: function (obj) { return obj.ItemCount; },
id: "0"
},
caption: getParticipantCaption(),//"Participants",
pgbuttons: false,
recordtext: "Total: {2}",
emptyrecords: "",
loadtext: "Loading...",
pgtext: "",
datatype: function () {
UpdateParticipant("getParticipants");
},
ajaxGridOptions: { contentType: 'application/json; charset=utf-8' },
// serializeGridData: function (postData) { return JSON.stringify(postData); },
colNames: ['Id', 'PERNR', 'Name', 'Email', 'RoleId', 'Role', 'Active', 'Updated'],
colModel: [
{ name: 'Id', index: 'Id', hidden: true, editable: true, hidedlg: true },
{ name: 'PERNR', index: 'PERNR', hidden: true, editable: true, hidedlg: true },
{ name: 'Name', index: 'Name', width: 200, align: "center", editable: true, edittype: "select",
editoptions: { value: function () {
var ITDdlItems = $.parseJSON($("input[id$='hdfITEmployeesDdlItems']").val());
var s = "";
if (ITDdlItems.Table4 && ITDdlItems.Table4.length) {
for (var i = 0, l = ITDdlItems.Table4.length; i < l; i++) {
var item = ITDdlItems.Table4[i];
s += item.PERNR + ":" + item.Name + ";";
}
}
s = s.substring(0, s.length - 1);
return s;
},
dataInit: function (e) {
$(e).multiselect({
maxHeight: 200,
enableFiltering: true,
filterPlaceholder: "Search Employees",
enableCaseInsensitiveFiltering: true,
templates: {
filter: '<li class="multiselect-item filter"><div class="input-group"><input class="form-control input-sm multiselect-search" id="txtITEmployeeFilter" type="text"></div></li>',
filterClearBtn: "<span class='input-group-btn'><button class='btn btn-default input-sm multiselect-clear-filter' type='button'><i class='glyphicon glyphicon-remove'></i></button><button class='btn btn-primary input-sm multiselect-clear-filter' type='button' onclick='javascript:searchEmployees("#" + e.id + "");'><i class='glyphicon glyphicon-search'></i></button></span>"
},
onDropdownHide: function (event) {
$(e).multiselect("updateButtonText");
$(e).multiselect("updateSelectAll");
}
// onChange: function(option, checked) {
// var selectedOption = $("#" + e.id + " option:selected").val();
// alert(selectedOption);
// }
});
}
}
},
{ name: 'Email', index: 'Email', width: 250, align: "center", editable: false },
{ name: 'RoleId', index: 'RoleId', hidden: true, editable: true, hidedlg: true },
{ name: 'Role', index: 'Role', width: 175, align: "center", editable: true, edittype: "select",
editoptions: { value: function () {
var roleDdlItems = $.parseJSON($("input[id$='hdfRoleDdlItems']").val());
var s = "";
if (roleDdlItems.Table3 && roleDdlItems.Table3.length) {
for (var i = 0, l = roleDdlItems.Table3.length; i < l; i++) {
var item = roleDdlItems.Table3[i];
s += item.Id + ":" + item.Role + ";";
}
}
s = s.substring(0, s.length - 1);
return s;
},
dataInit: function (e) {
$(e).multiselect({
maxHeight: 200,
onDropdownHide: function (event) {
$(e).multiselect("updateButtonText");
$(e).multiselect("updateSelectAll");
}
});
}
}
},
{
name: 'Active', index: 'Active', hidden: false, width: 75, align: "center", editable: true, hidedlg: true,
edittype: 'checkbox', editoptions: { value: "true:false", defaultValue: "Active" },
formatter: "checkbox", formatoptions: { disabled: true }
},
{ name: 'Updated', index: 'Updated', width: 100, align: "center", editable: false, sorttype: "date",
formatter: 'date', formatoptions: { newformat: 'n/j/y g:i A' }
}
],
rowNum: 5000,
autoWidth: true,
rowList: [],
pager: '#pgrParticipants',
toppager: true,
sortname: 'Name',
viewrecords: true,
sortorder: 'asc'
});
$('#grdParticipants').navGrid("#pgrParticipants", {edit: false, add: false, del: true, refresh: false, search: false, view: false});
$('#grdParticipants').inlineNav('#pgrParticipants',
// the buttons to appear on the toolbar of the grid
{
edit: true,
add: true,
del: true,
cancel: true,
editParams: {
keys: true
},
addParams: {
addRowParams: {
keys: true
}
}
});
$('#grdParticipants').navSeparatorAdd('#pgrParticipants', {
sepclass: 'ui-separator',
sepcontent: '',
position: 'last'
});
$('#grdParticipants').navButtonAdd('#pgrParticipants',
{
buttonicon: "ui-icon-help",
title: "Roles & Responsibilities Matrix",
caption: "Roles & Responsibilities Matrix",
position: "last",
onClickButton: showRoleMatrix
});
* EDIT *
The datatype function contains an ajax call that populates the grid. I’m using this based on an example someone else in my company provided. I’ll look around today for a better method, as it sounds this isn’t the best way. Maybe using url, which I stumbled across today.
This is a tab interface to track outages that will ultimately have a total of 5 separate JQGrids. When the page initially loads for a new outage this grid is on the first tab and is empty. It would only contain records if they’re editing an existing outage. In that instance, I would populate values in the main outage form controls and load data in the grid. The UpdateParticipant function seemed work well for this as it allows me to check for that hidden field before deciding whether a db call is even needed.
The PERNR is an employee id that the user doesn’t need to know, hence hidden. It’s not strictly confidential info, but we don’t advertise it either. They only need to see Name and Email (maybe) based on the value selected from the Name multiselect. Id will be a Participant Id generated by the database after the grid data is saved. Which can’t happen until the main outage form above is saved because I need that unique Outage Id as a foreign key for the participants. This attaches a participant to an outage and becomes the unique Id for the grid rows.
The selectedOption = $("#" + e.id + " option:selected").val() is commented out, but was only to trigger onchange for that specific Bootstrap Multiselect. The Role multiselect didn’t have an onchange function registered in code. So yes, it was for one element only. As mentioned previously, I was trying to use this to populate PERNR on a Name select. I need PERNR not Name to save to the db later. To solve for this I’m using the custom formatter on that column so I’ve since removed that onchange function for the Name multiselect. The ITDdlItems = $.parseJSON($("input[id$='hdfITEmployeesDdlItems']").val()) contains a json list of employee names and PERNRs to populate the Name multiselect. That works fine so this isn’t code relevant.
The only thing I need to figure out is how to perform a check for OutageId in the hidden field before the grid data is posted to the server. Thinking about it last night, if all else fails, I’ll let it post to the server and check there for the OutageId. I just don’t like posting if it isn’t going to make a db call. I’d share a demo somewhere if I knew how. This is an internal application so my options are limited.

jqGrid Switch a field to dropdown from text

Ive got a jqGrid where i have a some columns and 1 of the columns is a dropdownlist(select) populated from database.
What i want is : When im not in editmode column with dropdowns just have to show text which have to be taken from query, and when im in edit mode it should show dropdown list.
exactly like here: http://www.trirand.com/blog/jqgrid/jqgrid.html go into row editing/input tipyes
here is the code for my grid:
<script type="text/javascript">
var lastsel;
$(document).ready(function () {
$.getJSON('#Url.Action("ConstructSelect")', function (data) {
setupGrid(data);
});
});
function setupGrid(data) {
jQuery(document).ready(function () {
jQuery("#list").jqGrid({
url: '#Url.Action("GetStoreList")',
datatype: 'json',
mtype: 'GET',
colNames: ['Butiks kategori', 'Butik Navn', 'By', 'Sælger'],
colModel: [
{ name: 'Id', index: 'Id', width: 50 },
{ name: 'Butiks Kategori', index: 'StoreId', width: 200, edittype: 'text', align: 'center', editable: false },
{ name: 'Buttiks Navn', index: 'StoreName', width: 200, edittype: 'text', align: 'center', editable: false },
{ name: 'Country', index: 'Country', width: 80, sortable: true, editable: true, edittype: "select", editoptions: { value: data }}],
onSelectRow: function (id) {
if (id && id !== lastsel) {
jQuery('#list').jqGrid('restoreRow', lastsel);
jQuery('#list').jqGrid('editRow', id, true);
lastsel = id;
}
},
editurl: '#Url.Action("GridSave")',
rowNum: 50000,
rowList: [5, 10, 20, 50],
pager: '#page',
sortname: 'Id',
sortorder: "desc",
viewrecords: true,
height: "500px",
imgpath: '/scripts/themes/base/images'
});
jQuery("#list").jqGrid('navGrid', "#page", { edit: false, add: false, del: false });
});
}
</script>
P.S. Ill link code as soon as i am back home
UPDATED: Thanks for an answer, im new to jq, so im making alot of mistakes ofc., but now im back to where i was before, the dropdownlist is not populated with data. i cleaned up the code as u said, so it looks like this now:
btw. The ConstructSelect return a list of Strings
jQuery(document).ready(function () {
jQuery("#list").jqGrid({
url: '#Url.Action("GetStoreList")',
ajaxSelectOptions: { type: "POST", dataType: "json" },
datatype: 'json',
mtype: 'GET',
colNames: ['Butiks kategori', 'Butik Navn', 'By', 'Sælger'],
colModel: [
{ name: 'Kategori', index: 'Kategori', width: 50, key: false},
{ name: 'Navn', index: 'Navn', align: 'center', editable: false },
{ name: 'By', index: 'By', align: 'center', editable: false },
{ name: 'Sælger', index: 'Sælger', editable: true, edittype: "select",
editoptions: { dataUrl: '#Url.Action("ConstructSelect")',
buildSelect: function (data) {
var response = jQuery.parseJSON(data.responseText);
var s = '<select>';
if (response && response.length) {
for (var i = 0, l = response.length; i < l; i++) {
var ri = response[i];
s += '<option value="' + ri + '">' + ri + '</option>';
}
}
return s + "</select>";
}
}
}],
onSelectRow: function (id) {
if (id && id !== lastsel) {
jQuery('#list').jqGrid('restoreRow', lastsel);
jQuery('#list').jqGrid('editRow', id, true);
lastsel = id;
}
},
editurl: '#Url.Action("GridSave")',
rowNum: 50000,
rowList: [5, 10, 20, 50],
pager: '#page',
sortname: 'Id',
sortorder: "desc",
viewrecords: true,
height: "900px"
});
jQuery("#list").jqGrid('navGrid', "#page", {edit:false, add:false, del:false});
});
Okay, slight modifications was needed to get it working :
var response = typeof(data) === "string" ? jQuery.parseJSON(data.responseText):data;
aparently u have to tell buildselect that the data u want to modify is String
But i still have the problem that it doesnt show from begining which sellers is already selected!
Okay after restart it mysticly worked... it is solved now
What you need to do is to use
editoptions: { dataUrl: '#Url.Action("ConstructSelect")' }
instead of
editoptions: { value: data }
Depend on the format of the output of the action ConstructSelect you can need to use an additional property buildSelect of the editoptions. jqGrid expected that the server response on the HTTP 'GET' request of dataUrl will be HTML fragment which represent <select>. For example:
<select>
<option value="de">Germany</option>
<option value="us">USA</option>
</select>
If the server return other formatted data, like JSON data
["Germany","USA"]
or
[{"code":"de","display":"Germany"},{"code":"us","display":"USA"}]
you can write JavaScript function which convert the server response to the HTML fragment of the <select> and set the value of the property buildSelect to the function.
In the answer you will find an example of the function.
If your action support only HTTP POST and no GET you will have to use ajaxSelectOptions: { type: "POST" } parameter additionally, to overwrite the type of the corresponding ajax requests. In the same way you can overwrite other ajax parameters. For example you can use
ajaxSelectOptions: { type: "POST", dataType: "json"}
(defaults are type : "GET" and dataType: "html")
Some other small remarks to the code:
you should not place $(document).ready(function () { inside of another $(document).ready(function () {.
You use 'Id' instead of 'id'. So jqGrid will not find the id property. You can a) rename
'Id' to 'id' b) include additional parameter jsonReader: {id: 'Id'} c) include additional property key: true in the definition of the column 'Id'. Any from the ways will solve the described problem.
You can remove default properties like edittype: 'text', sortable: true or editable: false. See jqGrid documentation which describes the default values of all colModel properties.
You should remove imgpath parameter of jqGrid. The parameter is not exist since many many versions of jqGrid (see here).

jqgrid edit and add rows with "tab" key

I'm new to jqgrid , and I'm trying to navigate through the grid with "tab" key.
I want to be able to edit a row, and when I'm editing the last cell in that row, if I click the tab key it will save the current row changes (in the client side , and not by clicking enter) and set the focus to the next row and edit it's cells , and when I get to the last row and cell, the tab click will add a new row and make it in edit mode.
I tried with in line editing and then with cell editing but always got stuck...
how can this be done?
Thanks in advance.
I do not know what you currently have, but I tested this and it works. Since you failed to mention how you would originally begin editing the grid, I did it manually in the ready event, you just have to keep track of what row is currently being edited using the selIRow var.
var selIRow = 1; //keep track of currently edited row
//initialized to 1 for testing purposes
$(document).ready(function () {
$("#jqGrid").jqGrid({
datatype: 'local',
colNames: ['Inv No', 'Date', 'Client', 'Amount', 'Tax', 'Total', 'Notes'],
colModel: [
{ name: 'id', index: 'id', width: 60, editable: true },
{ name: 'invdate', index: 'invdate', width: 90, editable: true },
{ name: 'name', index: 'name', width: 100, editable: true },
{ name: 'amount', index: 'amount', width: 80, editable: true },
{ name: 'tax', index: 'tax', width: 80, editable: true },
{ name: 'total', index: 'total', width: 80, editable: true },
{ name: 'note', index: 'note', width: 150, editable: true,
//Place this code in the col options of the last column in your grid
// it listens for the tab button being pressed
editoptions: {
dataInit: function (elem) { $(elem).focus(function () { this.select(); }) },
dataEvents: [
{
type: 'keydown',
fn: function (e) {
var key = e.charCode || e.keyCode;
if (key == 9)//tab
{
var grid = $('#jqGrid');
//Save editing for current row
grid.jqGrid('saveRow', selIRow, false, 'clientArray');
//If at bottom of grid, create new row
if (selIRow++ == grid.getDataIDs().length) {
grid.addRowData(selIRow, {});
}
//Enter edit row for next row in grid
grid.jqGrid('editRow', selIRow, false, 'clientArray');
}
}
}
]
}
}
],
});
});
Some credit goes to kajo's answer from here for the tab event.

Resources