Update specific rows without reloading the JqGrid - javascript

I am current using a JqGrid for my data visualization.
Here is my JqGrid configurations.
$('#jqGrid').jqGrid({
url: '/ConfirmationOfEmployment/GetUsers',
mtype: "POST",
rowNum: currentPageSize,
datatype: "json",
colNames: ['UserId', 'First Name', 'Last Name', 'Email Address', 'Expiry Date', 'Remaining Days', 'Actions','Remind Status'],
colModel: [
{ name: 'UserId', index: 'UserId', align: 'left', hidden: true, edittype: 'text' },
{ name: 'FirstName', index: 'FirstName', align: 'left' },
{ name: 'LastName', index: 'LastName', align: 'left' },
{ name: 'Email', index: 'Email', align: 'left' },
{ name: 'userExpiryDate', index: 'ExpiryDate', align: 'center', classes: 'createdDate' },
{ name: 'remainingDays', index: 'RemainingDays', align: 'center' },
{ name: 'isReminded', index: 'isReminded', align: 'left', hidden: true, edittype: 'text' },
{ name: 'act', index: 'act' },
],
pager: $('#jqPager'),
sortname: currentSortName,
width: '700',
shrinkToFit: false,
sortorder: currentSortOrder,
search: true,
postData: {
filters: RetrieveFilters
},
gridComplete: function () {
var ids = jQuery('#jqGrid').jqGrid('getDataIDs');
var remindStatus = jQuery('#jqGrid').jqGrid('getCol', 'isReminded');
for (var i = 0; i < ids.length; i++) {
var userId = ids[i];
var isUserReminded = remindStatus[i];
var confrim = "<input style='height:25px;width:60px;margin-left:5px;' type='button' value='Confirm' onclick=\"ConfirmUser('" + userId + "','"+i+"');\" />";
var remove = "<input style='height:25px;width:60px;margin-left:5px;' type='button' value='Delete' onclick=\"DeleteUser('" + userId + "');\" />";
var remind;
if (isUserReminded == 'True') {
remind = "<input style='height:25px;width:60px;margin-left:5px;' type='button' disabled value='Remind' onclick=\"RemindUser('" + userId + "');\" />";
}
else {
remind = "<input style='height:25px;width:60px;margin-left:5px;' type='button' value='Remind' onclick=\"RemindUser('" + userId + "');\" />";
}
jQuery('#jqGrid').jqGrid('setRowData', ids[i], { act: confrim + remind + remove });
};
PageIndexHashUpdate();
}
});
In each of row, there are three buttons. Once user click on the "Confirm button" it fire the ConfirmUser javascript ajax call to the server and update the expiry date and the remaining days of the particular user.Once it's get succeeded, it will reload the grid.So its working fine.Here is the code.
ConfirmUser = function (selectedUserId, rowId) {
$.ajax({
url: "/ConfirmationOfEmployment/ConfirmUser",
async: false,
cache: false,
type: "POST",
dataType: "json",
data: { userId: selectedUserId },
error: function (jqXHR, textStatus, errorThrown) {
$.flashMessage({ "error": errorThrown, "alert": "error" });
},
success: function (data, textStatus, jqXHR) {
console.log(rowId);
console.log(data.newExpiryDate);
var rowData = $('#jqGrid').jqGrid('getRowData', rowId);
console.log(rowData);
//rowData.remainingDays = '180';
//rowData.userExpiryDate = data.newExpiryDate;
//$('#jqGrid').jqGrid('setRowData', rowId, rowData)
//$("#jqGrid").jqGrid('setCell', rowid, 'remainingDays', data.remaining);
//$("#jqGrid").jqGrid('getLocalRow', rowid).remainingDays = data.remaining;
$('#jqGrid').trigger("reloadGrid", [{ page: currentPage, current: true }]);
}
});
};
But the problem is that,once the user keep on clicking the confirm button for various user records, each and every time it will reload the grid which is much time consuming.So what I am seeking is a way to update the particular row only(instead of reloading the grid.)
I tried to use 'setCell' and 'setRowData' methods(commented out lines.) but I failed. So I would like to know how to do update particular cell or row without reloading the grid? Thank you.

Related

how to fill select dropdown from mysql in jqgrid

**> Hello, I'm a beginner developer.
When selecting 'largeCategoryZone', separate it with ASCIICode to
retrieve the value from db.
I'd like to put those values in the 'smallCategoryZone'. The content
below is my code. Please check and Please answer me.**
$(document).ready(function () {
$("#AdminCheckJqGrid").jqGrid({
url: "../barcode/barcodeAdminCheckInquiry/1",
datatype: "json",
loadtext: "loading...",
method: "GET",
postData: {
"certificateNumber": $("#certificateNumber").val()
},
colNames: ['sku', 'label', 'qty', 'realQty', 'palletType', 'palletBarcode','largeCategoryZone','middleCategoryZone','smallCategoryZone', 'remark'],
colModel: [
{label: 'sku', name: 'sku', width: '30', align: 'center'},
{label: 'label', name: 'label', width: '60', align: 'center'},
{label: 'qty', name: 'qty', width: '20', align: 'center'},
{label: 'realQty', name: 'realQty', width: 30,align: 'center', sortable: false, editable: true},
{label: 'palletType', name: 'palletType', width: 40, align: 'center', editable: true, edittype: 'select', editoptions: {dataUrl: '../code/palletType', buildSelect: setSelect}},
{label: 'palletBarcode', name: 'palletBarcode', width: 40, align: 'center', editable: true, edittype: 'select', editoptions: {dataUrl: '../code/palletBarcode', buildSelect: palletBarcodeSelect}},
{label: 'largeCategoryZone', name: 'largeCategoryZone', width: 40, align: 'center', editable: true, edittype: 'select', editoptions: {dataUrl: '../code/largeCategoryZone', buildSelect:setSelect ,
dataEvents: [{
type: 'change',
fn: function (e) {
var selectedData = e.currentTarget.value;
var dataFrist = selectedData.substr(0,1);
var dataAscii = dataFrist.charCodeAt();
$.ajax({
url: '../code/largeCategoryZone/' + dataAscii,
type: 'GET',
success: function (data) {
var jdata = jQuery.parseJSON(data).result;
var selectHtml = "";
for(var i=0; i < jdata.length; i++){
selectHtml += "<option value='" + jdata[i].subcode + "'>" + jdata[i].codename + "</option>";
}
if ($(e.target).is('.FormElement')) {
var form = $(e.target).closest('form.FormGrid');
console.log("form"+form);
$("select#smallCategoryZone.FormElement", form[0]).html(selectHtml);
} else {
var row = $(e.target).closest('tr.jqgrow');
var rowId = row.attr('id');
var rowId = jQuery("#AdminCheckJqGrid").jqGrid('getGridParam','selrow');
jQuery("select#" + rowId + "_smallCategoryZone").append(selectHtml);
}
}
});
}}]}},
{label: 'middleCategoryZone', name: 'middleCategoryZone', width: 40, align: 'center', editable: true, edittype: 'select', editoptions: {dataUrl: '../code/largeCategoryZone', buildSelect: setSelect}},
{label: 'smallCategoryZone', name: 'smallCategoryZone', width: 40, align: 'center', editable: true, edittype: 'select',editoptions: { } },
{label: 'remark', name: 'remark', width: 50, sortable: false, editable: true, align: 'center', editoptions: {autocomplete: "off"}},
],
});
});
Your code is working fine with last version of Guriddo jqGrid.
You will need to fine up your code.
First you will need to set a default value for smallCategoryZone when define the select in colModel
{label: 'smallCategoryZone', name: 'smallCategoryZone', width: 40, align: 'center', editable: true, edittype: 'select',editoptions: { value:":SelectCity" } },
Second: when calling ajax you will need to check that the data is here and use html instead of append for the inline edit the same as in form editing)
if ($(e.target).is('.FormElement')) {
var form = $(e.target).closest('form.FormGrid');
console.log("form"+form);
$("select#smallCategoryZone.FormElement", form[0]).html(selectHtml);
} else {
//var row = $(e.target).closest('tr.jqgrow');
//var rowId = row.attr('id');
var rowId = jQuery("#AdminCheckJqGrid").jqGrid('getGridParam','selrow');
jQuery("select#" + rowId + "_smallCategoryZone").html(selectHtml);
}
I solved dropDown with setCell
var check =
$("#moveZoneJqGrid").jqGrid("setCell",rowid,"moveToBarcode",selectHtml);
{label: 'moveToThird', name: 'smallCategoryZone', width: 25, align: 'center', editable: true, edittype: 'select',editoptions: {
dataEvents: [{
type: 'change',
fn: function(e) {
var rowid = e.originalEvent.path[2].id;
var rowval = $('#moveZoneJqGrid').jqGrid('getRowData', rowid);
var jdata = new Object();
var largeCategoryZone = rowval.largeCategoryZone;
var middleCategoryZone = rowval.middleCategoryZone;
var smallCategoryZone = e.currentTarget.value;
$.ajax({
url: "../barcode/getBarcodeFromZone",
method: "GET",
data : {
"largeCategoryZone" : largeCategoryZone,
"middleCategoryZone" : middleCategoryZone,
"smallCategoryZone" : smallCategoryZone,
},
dataType: "json",
success: function (data) {
var jdata = data.inquiryList
var selectHtml = "<select>";
for(var i=0; i < jdata.length; i++){
selectHtml += '<option value="' + jdata[i].barcode + '">' + jdata[i].barcode + '</option>';
}
selectHtml += "</select>";
var check = $("#moveZoneJqGrid").jqGrid("setCell",rowid,"moveToBarcode",selectHtml);
},
error: function(xhr, status, err){
alert(status + "\n" + err);
}
}); //ajax
} //fn function
}] // dataEvent
} //editoption
},
{label: 'moveToBarcode', name: 'moveToBarcode', width: '35', align: 'center', editable: true, edittype: 'select', editoptions: { }},

JQGrid can't load data from JSON showing empty grid

My JQGrid code is below
jQuery("#jqgrid").jqGrid({
mtype: 'GET',
datatype: "json",
height: '350',
colNames: ['<%=Resources.Resource.Action%>','uid', '<%=Resources.Resource.Fullname%>', '<%=Resources.Resource.Username%>', '<%=Resources.Resource.Group%>', '<%=Resources.Resource.Status%>', '<%=Resources.Resource.JoinedDate%>', '<%=Resources.Resource.LastLoginDate%>', '<%=Resources.Resource.LastLoginIp%>'],
colModel: [
{ name: 'act', index: 'act', sortable: false },
{ name: 'uid', index: 'uid' },
{ name: 'userfullname', index: 'userfullname' },
{ name: 'username', index: 'username' },
{ name: 'MemberGroup', index: 'MemberGroup', editable: true },
{ name: 'Status', index: 'Status', align: "right", editable: true },
{ name: 'JoinDate', index: 'JoinDate', align: "right", editable: true, editable: true, sorttype: "date", unformat: pickDate },
{ name: 'LastLoginDate', index: 'LastLoginDate', align: "right", editable: true, editable: true, sorttype: "date", unformat: pickDate },
{ name: 'LoginIp', index: 'LoginIp', sortable: false, editable: true }],
jsonreader: {
repeatitems: false, root: 'rootUser',
id: 'uid',
page: function(obj) { return 1; },
total: function(obj) { return 1; },
records: function (obj) { return obj.rootUser.length; },
},
rowNum: 10,
rowList: [10, 20, 30],
pager: '#pager_jqgrid',
sortname: 'uid',
rownumbers: true,
toolbarfilter: true,
viewrecords: true,
sortorder: "asc",
gridComplete: function () {
var ids = jQuery("#jqgrid").jqGrid('getDataIDs');
for (var i = 0; i < ids.length; i++) {
var cl = ids[i];
be = "<button class='btn btn-xs btn-default btn-quick' title='Edit Row' onclick=\"showPanelPlayer()\"><i class='fa fa-pencil'></i></button>";
//se = "<button class='btn btn-xs btn-default btn-quick' title='Save Row' onclick=\"jQuery('#jqgrid').saveRow('" + cl + "');\"><i class='fa fa-save'></i></button>";
//ca = "<button class='btn btn-xs btn-default btn-quick' title='Cancel' onclick=\"jQuery('#jqgrid').restoreRow('" + cl + "');\"><i class='fa fa-times'></i></button>";
//jQuery("#jqgrid").jqGrid('setRowData', ids[i], { act: be + se + ca });
jQuery("#jqgrid").jqGrid('setRowData', ids[i], { act: be });
}
},
editurl: "ajax/dummy-jqtable.html",
caption: "<%=Resources.Resource.MemberListing%>",
multiselect: true,
autowidth: true,
});
When I click submit button it will call my backend page and generate Json .
My Submit button code is
function showPanel() {
var UserName = document.getElementById('txtUser').value;
$('#jqgrid').setGridParam({ url: 'ListUser.aspx?cmd=LoadUser&UN=' + UserName }).trigger('reloadGrid');
}
The Json Return from back end is
{"rootUser":[{"uid":1,"userfullname":"Johnson","username":"Deng","MemberGroup":0,"Status":1,"JoinDate":new Date(1487058713667),"LastLoginDate":new Date(1487058713667),"LoginIp":""},{"uid":2,"userfullname":"James Abb","username":"James","MemberGroup":0,"Status":1,"JoinDate":new Date(1487058713667),"LastLoginDate":new Date(1487058713667),"LoginIp":""}]}
The problem is i facing is my grid show empty , is that anything i missing out form my code ?
The input data are not in JSON format because of usage fields like "JoinDate": new Date(1487058713667). You can validate JSON data here: http://jsonlint.com/. The fix of the problem depends on the version of jqGrid, which you use and from fork of jqGrid (free jqGrid, commercial Guriddo jqGrid JS or an old jqGrid in version <=4.7). Free jqGrid for example allows to use formatoptions: { srcformat: "u1000", newformat: "d-M-Y H:i:s" } to parse the data from"JoinDate": 1487058713667 to 14-Feb-2017 08:51:53. You can use, of cause, other newformat.
I'd recommend you additionally never use gridComplete with the loop, where you call setRowData. The usage of custom formatter or formatter: actions is much more effective.

Check specific check box in kendo grid

i want to loop through each row of kendo grid and check the check box of specific rows only.here's what i have tried so far.
function LoadControllerGrid(list) {
$("#controllerGrid1").kendoGrid({
data Source: {
type: "json",
// contentType: "application/json; charset=utf-8",
transport: {
read: {
url: "#Html.Raw(Url.Action("GetControllerList", "Account"))",
type: "POST",
dataType: "json"
},
},
schema: {
model: {
id: "Id",
fields: {
'Id': { type: "string" },
'Name': { type: "string" },
'Description': { type: "string" },
'URL': { type: "string" },
},
},
data: 'data',
total: 'TotalCount'
},
complete: function (jqXHR, textStatus) {
// HidePageLoader();
},
pageSize: 5,
serverPaging: true,
serverSorting: true,
serverFiltering: true,
columnMenu: true
},
height: 300,
groupable: false,
sortable: true,
filterable: true,
pageable: {
refresh: true,
pageSizes: 5000
},
columns: [{ template: '<input type="checkbox" id="#=Id#" class="gridCK" />', width: "35px" },
{ field: "Description", title: "Actions" }, ]
});
var df = list;
var grid = $("#controllerGrid1").data("kendoGrid");
grid.tbody.find("input").closest("tr").each(function (index, row) {
var dataItem = grid.dataItem(row);
for (var i = 0; i < df.length; i++)
{
if (df[i] == dataItem.Id) {
$("#controllerGrid1 tbody").find("tr[data-uid=" + dataItem.Id + "]").attr("checked");
});
}
can any one explain what did i do wrong?? and suggest if there are any alternative ways of doing this. Thanks in advance
I found a solution.
var selected = $("#controllerGrid1 tbody").find("tr[data-uid=" + dataItem.uid + "]");
selected
.find("td:first input")
.attr("checked", true);
It works for me after adding above code instead of following,
$("#controllerGrid1 tbody").find("tr[data-uid=" + dataItem.Id + "]").attr("checked");

Unable to bind the data to dropdown in jqgrid when it is editing getting data using web api

$j(document).ready(function () {
$j.ajax({
type: "GET",
url: "http://localhost:9611/api/Master/GetBackendUsersList",
contentType: "json",
dataType: "json",
success: function (data) {
var dataList;
var StatusList = '';
$j('#list2').jqGrid({
caption: "Users Details",
data: data,
datatype: "local",
height: '100%',
width: '100%',
colNames: ["UserName", "RoleId", "Name", "RoleName", "LoginId"],
colModel: [
{ name: "UserName", index: 'UserName', editable: true },
{ name: 'RoleId', index: "RoleId", hidden: true, width: 150, editable: true },
{ name: "Name", index: "Name", editable: true },
{
name: "RoleName", index: "RoleName", editable: true, edittype: 'select', editoptions: {
dataInit: function (element)
{
$j.ajax({
type: "GET",
url: "http://localhost:9611/api/Master/GetRoles",
contentType: "json",
dataType: "json",
success: function (mydata) {
dataList = mydata;
for (var i = 0; i < dataList.length; i++) {
//if (StatusList == "")
// StatusList = dataList[i].RoleId + ":" + dataList[i].RoleName;
//else
StatusList = StatusList + dataList[i].RoleId + ":" + dataList[i].RoleName+ ';' ;
}
}
});
},
value: "0:Select;" + StatusList,
}
},
{ name: 'LoginId', index: "LoginId", hidden: true, width: 150 }
],
gridview: true,
rowNum: 5,
rowList: [5, 10, 15],
pager: '#jQGridDemoPager',
sortname: "UserName",
viewrecords: true,
sortorder: "desc",
//width: '100%',
//height: '100%',
shrinkToFit: false,
editurl: SiteUrl + "api/Master/UpdateBackendUserDetails/" ,
});
$j.extend(true, $j.jgrid.edit, {
recreateForm: true,
beforeShowForm: function ($jform) {
$jform.closest(".ui-jqdialog").position({
of: window, // or any other element
my: "center center",
at: "center center"
});
}
});
$j('#list2').jqGrid('navGrid', '#jQGridDemoPager',
{
add: false,
search: false,
recreateForm: true,
beforeShowForm: function ($jform) {
$jform.find(".FormElement[readonly]")
.prop("disabled", true)
.addClass("ui-state-disabled")
.closest("LoginId")
.prev(".CaptionTD")
.prop("disabled", true)
.addClass("ui-state-disabled");
},
},
{ recreateForm: true }
);
}
});
});
Dropdown data from api is like:
[{"RoleId":1,"RoleName":"Administrator"},{"RoleId":2,"RoleName":"Sales"},{"RoleId":3,"RoleName":"Secretory/President"},{"RoleId":4,"RoleName":"Apartment Owner"},{"RoleId":5,"RoleName":"Apartment User"}]
Use this way :
editoptions:{value: getData()}
and then create one method
function getData(){
var states = [{"RoleId":1,"RoleName":"Administrator"},{"RoleId":2,"RoleName":"Sales"},{"RoleId":3,"RoleName":"Secretory/President"},{"RoleId":4,"RoleName":"Apartment Owner"},{"RoleId":5,"RoleName":"Apartment User"}];
return states;
}
In your case you need to add ajax call in getData() and return values/array which has been created by the result.

Jqgrid custom formatter button click not working

I created a grid and one of my column has a custom button in each row. When I click the button my click event is not invoked.
My jqgrid:
$('#QuoteLineTable').jqGrid({
url: $('#url').val(),
datatype: 'json',
type: 'POST',
postData: { Id: $("#Id").val() },
colNames: ['Id', 'Quote Number', 'Valid Until Date','View Line Item'],
colModel: [
{ name: "QuoteLineId", index: "QuoteLineId", hidden: false, hidedlg: true },
{ name: 'QuoteNumber', index: "QuoteNumber" },
{ name: 'ValidUntil', formatter: "date", formatoptions: { newformat: "d/m/Y" }, width: '100px' },
{ name: 'View Line Item', formatter: viewLineBtn }
],
multiselect: true,
emptyrecords: "No Quote Line to view",
gridview: true,
autoencode: true,
loadtext: "Loading...",
loadonce: true,
rowNum: 3,
rowList: [10, 20, 30],
pager: '#LinePager',
height: '100%',
caption: "Quote List",
autowidth: true,
sortname: 'QuoteNumber',
ajaxGridOptions: { type: 'POST', contentType: "application/json; charset=utf-8" },
jsonReader: {
repeatitems: false,
root: "rows",
page: "page",
total: "totalPages",
records: "totalRecords",
id: "QuoteLineId"
},
serializeGridData: function(postData) {
return JSON.stringify(postData);
},
onCellSelect: function(rowid,e) {
alert("rowid=" + rowid );
},
ondblClickRow: function(rowid) {
var $model = $('#LineItemMyModal');
$.ajax({
type: "GET",
url: $('#urlItemDetails').val(),
data: { LineId: rowid },
success: function(r) {
$model.html(r);
$model.modal('show');
}
});
}
}).navGrid('#QuoteLinePager', { edit: false, add: false, del: false, search: true });
function viewLineBtn(cellvalue, options, rowObject) {
return "<button class=\"viewLineItem\">View Line Item</button>"
};
$('.viewLineItem').click(function (rowId) {
alert("hi");
alert(rowId);
});
Basically I am not sure how to call the click event for button class= viewLineItem.
I tried to use onCellSelect or beforeSelectRow event but I also need to use ondblClickRow to populate a modal. So I am looking for other options without using oncellSelect.
Try something like this.
$('#QuoteLineTable').jqGrid({
url: $('#url').val(),
datatype: 'json',
type: 'POST',
postData: { Id: $("#Id").val() },
colNames: ['Id', 'Quote Number', 'Valid Until Date','View Line Item'],
colModel: [
{ name: "QuoteLineId", index: "QuoteLineId", hidden: false, hidedlg: true },
{ name: 'QuoteNumber', index: "QuoteNumber" },
{ name: 'ValidUntil', formatter: "date", formatoptions: { newformat: "d/m/Y" }, width: '100px' },
{ name: 'View Line Item', formatter: viewLineBtn }
],
multiselect: true,
emptyrecords: "No Quote Line to view",
gridview: true,
autoencode: true,
loadtext: "Loading...",
loadonce: true,
rowNum: 3,
rowList: [10, 20, 30],
pager: '#LinePager',
height: '100%',
caption: "Quote List",
autowidth: true,
sortname: 'QuoteNumber',
ajaxGridOptions: { type: 'POST', contentType: "application/json; charset=utf-8" },
jsonReader: {
repeatitems: false,
root: "rows",
page: "page",
total: "totalPages",
records: "totalRecords",
id: "QuoteLineId"
},
serializeGridData: function(postData) {
return JSON.stringify(postData);
},
onCellSelect: function(rowid,e) {
alert("rowid=" + rowid );
},
ondblClickRow: function(rowid) {
var $model = $('#LineItemMyModal');
$.ajax({
type: "GET",
url: $('#urlItemDetails').val(),
data: { LineId: rowid },
success: function(r) {
$model.html(r);
$model.modal('show');
}
});
}
}).navGrid('#QuoteLinePager', { edit: false, add: false, del: false, search: true });
function viewLineBtn(cellvalue, options, rowObject) {
var rowid= options.rowid;
var button = "<button class=\"viewLineItem\" id="+ rowid+">View Line Item</button>"
$('#' + rowid).die();
$('#' + rowid).live('click', function (rowId) {
alert("hi");
alert(rowId);
});
};
It works for me:
$('#QuoteLineTable').jqGrid({
....
colModel: [
...
{ name: 'View Line Item', formatter: viewLineBtn }
]
loadComplete: function (data) {
console.log(data); // You can view the object
let rowDataArray = data.rows;
for (let i = 0, j = rowDataArray.length; i < j; i++)
{
let temp = rowDataArray[i];
$("#btn_" + temp.id).click(() => {
m_alert(temp.content);
});
}
}
});
function viewLineBtn(cellvalue, options, rowObject)
{
return "<button id='btn_" + rowObject.id + "'>View Line Item</button>"
}

Categories

Resources