Jqgrid custom formatter button click not working - javascript

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>"
}

Related

Cannot read property 'length' of null in script

I'm trying to call a function from code behind in script. That function i just returning list of employee
i'm just trying not to use grid view.
I just copy the code in at the same project and changes the names of function and the name inside the colModel: []
here's my script:
function loadMoretha60grid() {
$('#timesheetgrid').jqGrid("GridUnload");
getmoreThan60(function (data) { loadTimesheetTableMoeretha60(data); });
}
function loadTimesheetTableMoeretha60(timelog) {
var lastsel;
var startpage = 1;
$('#timesheetgrid').jqGrid({
datatype: 'local',
data: timelog,
editurl: 'clientArray',
colNames: ['CompanyID', 'EMPName', 'START_DATE', 'END_DATE',
'TOTALHOURS'],
colModel: [
{ name: 'CompanyID', index: 'CompanyID', editable: 'false', align: 'center', width: '150', sortable: false, },
{ name: 'EMPName', index: 'EMPName', editable: 'false', align: 'center', width: '275', resizable: false },
{ name: 'START_DATE', index: 'START_DATE', editable: 'false', align: 'center', width: '175', resizable: false },
{ name: 'END_DATE', index: 'END_DATE', editable: 'false', align: 'center', width: '175', resizable: false },
{ name: 'TOTALHOURS', index: 'TOTALHOURS', editable: 'false', align: 'center', width: '175', resizable: false },
],
pager: '#timesheetgridpager',
viewrecords: true,
forceFit: false,
shrinkToFit: false,
width: '1000',
emptyrecords: "No Record/s found",
loadtext: "Loading",
rowList: [5, 10, 20, 50],
height: 'auto',
caption: 'Timesheet Listing'
});
$('#timesheetgrid').jqGrid('navGrid', '#timesheetgridpager', {
edit: false,
save: false,
add: false,
cancel: false,
del: false,
search: false,
refresh: false
});
$('#timesheetgrid').jqGrid('inlineNav', '#timesheetgridpager', {
add: false,
edit: false,
save: false,
cancel: false,
restoreAfterSelect: false
});
}
function getmoreThan60(callback) {
var timelog = [],
params = {
name: $('#empnamebox').val(),
dateStart: '2019-09-01',
dateEnd: '2019-09-29'
};
showLoadingGif();
$.ajax({
async: true,
type: 'POST',
contentType: 'application/json',
url: baseUrl + 'Timesheet.aspx/getMore60hrs',
data: JSON.stringify(params),
dataType: 'json',
success: function (data) {
timelog = data.d;
hideLoadingGif();
if (typeof callback != 'undefined')
callback(timelog);
},
error: function (xhr, status, error) {
console.log(xhr, status, error);
hideLoadingGif();
}
});
}
here's my method
[WebMethod]
public static void getMore60hrs(string name,string dateStart,string dateEnd) {
TDKDataAccessLayer dataAcc = new TDKDataAccessLayer();
List<morethan> records = new List<morethan>();
dataAcc.DepartID = Convert.ToInt32(DeptID);
dataAcc.Name = name;
dataAcc.DateStart = dateStart;
dataAcc.DateEnd = dateEnd;
records = dataAcc.MoreThan60hrs();
}
By the way
I don't know what to do about this because i came from windows form c#

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 doesn't rise ondblClickRow event when filter applied

This is event calling filtering while typing:
$("#txtPickItem").change(function (e) { doSearchPick(); });
This is my jqGrid:
$("#gridChooseItems").GridUnload();
jQuery("#gridChooseItems").jqGrid({
url: 'MyURL', datatype: "JSON",
colNames: ['id', 'Group', 'Source order'...],
colModel: [
{ name: 'del', index: ' ', width: 28, hidden: true },
{ name: 'id', index: 'id', hidden: true },
{ name: 'Group', index: 'Group', hidden: true },
{ name: 'Code', index: 'Code', width: 180 }...
],
loadComplete: function () { if ($("#txtPickItem").val()) { setTimeout('doSearchPick();', 100); } },
rowNum: 25, rowList: [10, 25, 50, 100, 200],
pager: '#pagerChooseItems',
sortname: 'id',
ondblClickRow: function (id) { AddItem(id); },
height: 580,
width: 1050,
ignoreCase: true,
loadonce: true,
viewrecords: true,
sortorder: "desc",
caption: "Available items"
});
My filtering function:
function doSearchPick() {
var grid = $("#gridChooseItems");
var filter = {
"groupOp": "AND", "rules":
[
{ "field": "Supplier", "op": "cn", "data": $("#txtPickItem").val() }
]
};
grid.jqGrid('setGridParam', { search: true, postData: { filters: filter } });
grid.trigger("reloadGrid", [{ page: 1 }]);
}
I have to reload grid after doubleclick and apply filter so previously double clicked item is not in grid anymore (many things happens in between).
When $("#txtPickItem") is empty, ondblClickRow and everything works fine, filtering works fine too.
Problem is that when some text is contained in txtPickItem, ondblClickRow doesn't fire and I don't understand why. I need this ondblClickRow event desperately.
EDIT:
AddItem function works fine as everything else if $("#txtPickItem") is empty
function AddItem(id) {
pData = {}
pData["ItemID"] = id;
jQuery.ajax({
url: 'URL',
type: "POST",
dataType: "JSON",
data: pData,
success: function (data) {
if (data == "msg1") {
PopulatePickGridItems(); //fill some other grid
}
else if (data == "msg2") {
$("#divMsg").html("<ul><li>err1. msg.</li></ul>")
$('#dlgMsg').dialog('open');
}
else {
$("#divMsg").html("<ul><li>err2. msg.</li></ul>")
$('#dlgMsg').dialog('open');
}
}
});
}

Add/edit/delete in jqGrid with Web API

I am new to jqGrid and need some help on form add/edit/delete functionality. Havent found any relevant resources so far. My grid is displaying pop up on add/edit, also populating data on clicking edit, however I am not sure what should be javascript code to invoke the Web api to POST/PUT/DELETE the data.
Details below:
JSON data:
[{"Id":1,"BankId":2,"BankName":"State bank","EmployeeId":2539,"EmployeeName":"John C.","JoiningDate":"2005-07-05T00:00:00","SalaryAmount":50000.0,"Comments":""},
{"Id":2,"BankId":2,"BankName":"State bank","EmployeeId":2232,"EmployeeName":"xxx","JoiningDate":"2001-12-23T00:00:00","SalaryAmount":30000.0,"Comments":"test"},
{"Id":3,"BankId":4,"BankName":"National bank","EmployeeId":2322,"EmployeeName":"yyyy","JoiningDate":"2002-09-23T00:00:00","SalaryAmount":90000.0,"Comments":""},
{"Id":4,"BankId":3,"BankName":"Punjab bank","EmployeeId":2432,"EmployeeName":"ppp","JoiningDate":"2003-01-31T00:00:00","SalaryAmount":60000.0,"Comments":" "},
{"Id":5,"BankId":1,"BankName":"Bank of Maharashtra","EmployeeId":2892,"EmployeeName":"zzz y.","JoiningDate":"2000-10-11T00:00:00","SalaryAmount":80000.0,"Comments":"test 2"}
]
Javascript for jqGrid:
jQuery(document).ready(function () {
jQuery("#employeeSalarysGrid").jqGrid({
height: 250,
url: 'http://localhost:50570/api/Test/GetEmployeeSalaries',
mtype: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
serializeGridData: function (postData) {
return JSON.stringify(postData);
},
jsonReader: {
root: function (obj) { return obj; },
page: function (obj) { return 1; },
total: function (obj) { return 1; },
records: function (obj) { return obj.length; },
id: "0",
cell: "",
repeatitems: false
},
datatype: "json",
colNames: ['Id', 'Bank Name', 'Employee name', 'Joining date', 'Salary amount', 'Comments'],
colModel: [
{ name: 'Id', align: "center", hidden:true},
{ name: 'BankName', align: "center", editable: true },
{ name: 'EmployeeName', align: "center", editable: true },
{ name: 'JoiningDate', align: "center", editable: true },
{ name: 'SalaryAmount', align: "center", editable: true },
{ name: 'Comments ', align: "center", editable: true }
],
gridview: true,
autoencode: true,
ignorecase: true,
loadonce: true,
sortname: "InstallmentDate",
sortorder: "asc",
viewrecords: true,
rowNum: 10,
rowList: [10, 15, 20],
pager: '#employeeSalarysPager',
caption: "Employee Salary list"
});
$("#employeeSalarysGrid").jqGrid('navGrid', '#employeeSalarysPager',
{
add: true,
edit: true,
del: true
},
editOption,
addOption,
delOption);
var editOption =
{
width: 400, height: 290, left: 20, top: 30,
reloadAfterSubmit: false, jqModal: false, editCaption: "Edit Record",
bSubmit: "Submit", bCancel: "Cancel", closeAfterEdit: true,
mtype: "POST",
url: 'http://localhost:50570/api/Test/'
};
var addOption = {
width: 400, height: 290, left: 20, top: 30,
reloadAfterSubmit: false, jqModal: false, addCaption: "Add Record",
bSubmit: "Submit", bCancel: "Cancel",
closeAfterAdd: true,
mtype: "PUT",
url: 'http://localhost:50570/api/Test/'
};
var delOption = {
caption: "Delete",
msg: "Delete selected record(s)?",
bSubmit: "Delete", bCancel: "Cancel",
mtype: "DELETE",
url: 'http://localhost:50570/api/Test/'
};
});
Server side API signatures:
public HttpResponseMessage Post(int id, DTOTest value)
public HttpResponseMessage Put(DTOTest value)
public HttpResponseMessage Delete(int id)
Please let me know what is wrong with the code. Methods are not getting invoked. Am i missing anything in html code for jqGrid, OR are the signatures on server code needs to be modified?
Looking forward for some pointers.
Many thanks,
Abhilash
`var URL = 'rest/book';`
...
var delOptions = {
onclickSubmit: function(params, postdata) {
params.url = URL + '/' + postdata;
}
};
you mean this?
it might need "editurl" in your grid instead of "url" in the del(add/edit)Option,like this:
...
height: 250,
editurl: 'http://localhost:50570/api/Test/',
url: 'http://localhost:50570/api/Test/GetEmployeeSalaries',
mtype: "GET",
contentType: "application/json; charset=utf-8",
...
Have a try ?
You need to add URL parameter in your editOption, addOption, deleteOption
var editOption = {
width:400,
height:290,
left:20,
top:30,
reloadAfterSubmit:false,
jqModal:false,
editCaption: "Edit Record",
bSubmit: "Submit",
bCancel: "Cancel",
closeAfterEdit:true,
url:'http://localhost:50570/api/Test/EditEmployee'
};
var addOption = {
width:400,
height:290,
left:20,
top:30,
reloadAfterSubmit:false,
jqModal:false,
addCaption: "Add Record",
bSubmit: "Submit",
bCancel: "Cancel",
closeAfterAdd:true,
url:'http://localhost:50570/api/Test/AddEmployee'
};
var delOption = {
caption: "Delete",
msg: "Delete selected record(s)?",
bSubmit: "Delete",
bCancel: "Cancel",
url:'http://localhost:50570/api/Test/DeleteEmployee'
};

Categories

Resources