JQGrid with fontAwesome icon click event - javascript

I have a JQGrid in which one of the columns I used font awesome icon[X] to perform delete row operation. Below is the code where I used delete() function, expected that when I click on the div element the function would hits but does not happened and getting an error in developer tool like
"(function(event){DeselectMeasures(85)})", where 85 is the Id of my grid data.
Which is the best practice to perform this? Is there any alternative to produce [X] button as a last column and need to perform some operation before deleting?
$("#selectedMeasuresgridID").jqGrid({
datatype: 'function',
mtype: 'Post',
colNames: [ 'Delete'],
colModel: [
{ name: 'Delete', index: 'Delete', width: 50, editable: true, formatter: FACloseIcon, align: 'center' }
],
rowNum: 10,
rowList: [10, 20, 30, 40],
height: '100%',
viewrecords: true,
caption: '',
emptyrecords: 'No records to display',
autowidth: true,
loadComplete: function () {
//operations
}
});
function FACloseIcon(cellvalue, options, rowObject) {
return '<div onclick="Deselect(' + rowObject.Id + ')" class="fa fa-close deSelect" aria-hidden="true"></div>';
}
function Deselect(rowObject) {
//I will write code accordingly
}

Related

Why won't data output to jqGrid without the use of "hiddengrid: true"?

I want this:
Without having to start like this:
But for some reason the data only shows up when I use "hiddengrid: true,"
I tried following this demo and was only able to get the example to work by adding "hiddengrid: true," like so:
<body>
<div class="center" id="overGrid">
<table id="jqGrid"></table>
<div id="jqGridPager"></div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("#jqGrid").jqGrid({
url: 'api/codes',
editurl: 'api/codes',
colModel: [
{
label: "Edit Actions",
name: "actions",
width: 75,
formatter: "actions",
formatoptions: {
keys: true,
editOptions: {},
addOptions: {},
delOptions: {}
}
},
{
label: 'Id',
name: 'id',
width: 150,
editable: true
},
{
label: 'Title',
name: 'title',
width: 100,
editable: true
},
{
label: 'Code',
name: 'code',
width: 100,
editable: true
},
{
label: 'Original Url',
name: 'originalUrl',
width: 200,
editable: true
}
],
align: 'center',
viewrecords: true,
rowList: [10, 20, 30],
width: 925,
height: 445,
rowNum: 20,
loadonce: true,
hiddengrid: true, // <-------------------- HERE
toppager: '#jqGridPager',
pager: '#jqGridPager',
caption: "Database"
}); jQuery("#jqGrid")
.navGrid('#pager', { edit: false, add: false, del: false, search: false })
.navButtonAdd('#pager', {
caption: "Add",
buttonicon: "ui-icon-add",
onClickButton: function () {
alert("Adding Row");
},
position: "last"
})
.navButtonAdd('#pager', {
caption: "Del",
buttonicon: "ui-icon-del",
onClickButton: function () {
alert("Deleting Row");
},
position: "last"
});
function fetchGridData() {
var gridArrayData = [];
// show loading message
$("#jqGrid")[0].grid.beginReq();
$.ajax({
url: 'api/codes',
mtype: 'POST',
datatype: 'JSON',
success: function (result) {
for (var i = 0; i < result.items.length; i++) {
var item = result.items[i];
gridArrayData.push({
id: item.id,
title: item.title,
code: item.code,
originalUrl: item.originalUrl,
});
}
// set the new data
$("#jqGrid").jqGrid('setGridParam', { data: gridArrayData });
// hide the show message
$("#jqGrid")[0].grid.endReq();
// refresh the grid
$("#jqGrid").trigger('reloadGrid');
}
});
}
fetchGridData();
});
</script>
</body>
Examples such as this don't seem to be working for me on their own so I keep having to reference other sources such as this that are much more complex and informative but possibly the reason for why I continue to have issues every step of the way.
Side Note
I should probably point out that I was only just recently introduced to jqGrid as a result of this question I asked about a week ago: " How can I separate my output using “onclick” and format the data to 20 per page?
"
I did a fairly decent job of documenting the steps that brought me to this point so it might be worth checking out for an in depth look as to what I am dealing with.
In short I am building an API in Asp.Net Core that sends and receives JSON data to my MongoDb database and then outputs the data to a single HTML page using jqGrid. So far I have created functioning Get, Post, Put, and Delete methods that return and send JSON data to my MongoDb database.
Update:
I have gone through the docs suggested by Tony Tomov and I understand their meaning. I just haven't the slightest clue to the solution to this problem. Everything I have thought to be a possible solution and tried from before and after I posted this question has given me a blank page without any errors.

Free jqGrid, don't send new index on addrow with inlineNav

Just putting in a new grid, and everything seems to be working well, except for one thing. Using basic inline, it is sending a new incorrect key value for the column I have set with key: true. This is an auto-increment column in the database, so I just don't want to send any data for this column when ADDING, only for edit or delete is that required.
It is posting a parameter: row_id => jqg3 for the new key column and messing up my server script. So because adding the new row will auto-increment the row_id col, I don't need to send this.
How do I stop the jqGrid from sending this (row_id) index column value when saving a new added row?
free-jqgrid version is 4.14.0
$('#accts').jqGrid({
url:'/phpAJAX/Master/master_grid_v1.php',
editurl:'/phpAJAX/Master/master_grid_v1.php',
height: 'auto',
shrinkToFit: false,
width: 'auto',
datatype: 'xml',
mtype: 'POST',
postData:{
'arg1':'bol_acct'
},
colNames:[
'row_id',
'Customer',
'Trucker',
'Acct Num'
],
colModel:[
{name: 'row_id', hidden: true, key: true},
{name:'Customer', align: "center", editable: true},
{name: 'Trucker', align: "center"},
{name: 'Acct_Num', align: "center"}
],
sortname: 'Customer',
sortorder: 'desc',
viewrecords: true,
gridview: true,
caption: 'Bill of Lading Accounts',
rowNum: 10000,
pager:true
}).jqGrid('inlineNav', {
addParams: {
addRowParams: { extraparam: {'arg1':'bol_acct', 'oper':'add'} }
},
editParams: {
extraparam: {
'arg1':'bol_acct', 'oper':'edit'
}
}
})
One can use serializeSaveData callback of inline editing to modify the data, which will be send during inline editing. You can add serializeSaveData callback via
inlineEditing: {
keys: true,
extraparam: { arg1: "bol_acct" },
serializeSaveData: function (postData) {
var newPostData = $.extend(true, {}, postData);
if (newPostData.oper === "add") {
delete newPostData.id; // delete id parameter
}
return newPostData;
}
}

Jqgrid is empty, does not load json data from main grid

My subgrid only shows the column headers but not not load the json data from the main grid. The columns are empty. I followed the tutorial on JQuery Grid-SubGrid for Parent-Child relation
but it does not work.
This is my javascript code:
jQuery().ready(function () {
var grid = jQuery("#shipment_grid");
var mainGridPrefix = "s_";
grid.jqGrid({
url: '${pageContext.request.contextPath}/getTruckShipmentJSONAction?truckId=' + <c:out value="${truckId}" />,
datatype: "json",
mtype: 'GET',
loadonce: true,
colNames: ['Lead Tracking #'],
colModel: [
{name: 'trackingNr', index: 'trackingNr', width: 100, align: 'left'}
],
rowNum: 10,
height: 230,
width: 700,
idPrefix: mainGridPrefix,
autoheight: true,
rowList: [10, 20, 30],
pager: jQuery('#shipment_grid_pager'),
sortname: 'trackingNr',
sortorder: "desc",
jsonReader: {
root: "records",
page: "page",
total: "total",
records: "rows",
repeatitems: false
},
viewrecords: true,
altRows: false,
gridview: true,
multiselect:true,
hidegrid: false,
shrinkToFit: true,
forceFit: true,
idPrefix: mainGridPrefix,
caption: "Shipments Overview",
subGrid: true,
beforeProcessing: function(data) {
//align 'Lead Tracking #' column header to the left
grid.jqGrid ('setLabel', 'trackingNr', '', {'text-align':'left'});
var rows = data.rows, l = rows.length, i, item, subgrids = {};
for (i = 0; i < l; i++) {
item = rows[i];
if (item.shipUnitView) {
subgrids[item.id] = item.shipUnitView;
}
}
data.userdata = subgrids;
},
subGridRowExpanded: function (subgridDivId, rowId) {
var $subgrid = $("<table id='" + subgridDivId + "_t'></table>"),
pureRowId = $.jgrid.stripPref(mainGridPrefix, rowId),
subgrids = $(this).jqGrid("getGridParam", "userData");
$subgrid.appendTo("#" + $.jgrid.jqID(subgridDivId));
$subgrid.jqGrid({
datatype: "local",
data: subgrids[pureRowId],
colNames: ['Ship Type (Pallet / Carton)', 'Ship Unit (Pallet ID / Cone #)', 'Total Cartons'],
colModel: [
{ name: "shipUnitType", index: 'shipUnitType', width: 100, align: 'center'},
{ name: "reference", index: 'reference', width: 100, align: 'center'},
{ name: "totalOfCartons", index: 'totalOfCartons', width: 100, align: 'center'}
],
sortname: "shipUnitType",
sortorder: "desc",
height: "100%",
rowNum: 10,
autowidth: true,
autoencode: true,
jsonReader: {
root: "records",
records: "rows",
repeatitems: false,
id: "reference" },
gridview: true,
idPrefix: rowId + "_"
});
}
}).navGrid('#shipment_grid_pager', {edit: false, add: false, del: false, search: false, refresh: true});
});
This is my json data from the server:
{"page":1,
"records":[
{"id":2,"trackingNr":"1Z1484366620874728",
"shipUnitView":[{"reference":"65000943","shipUnitType":"CARTON","totalOfCartons":1},
{"reference":"65000942","shipUnitType":"CARTON","totalOfCartons":1}]},
{"id":4, "trackingNr":"1Z1484366620874746"
"shipUnitView":[{"reference":"65000940","shipUnitType":"CARTON","totalOfCartons":1},
{"reference":"65000939","shipUnitType":"CARTON","totalOfCartons":1}]},
{"id":3, "trackingNr":"1Z1484366620874764"
"shipUnitView":[{"reference":"65000938","shipUnitType":"CARTON","totalOfCartons":1},
{"reference":"65000937","shipUnitType":"CARTON","totalOfCartons":1}]}
],
"recordsTotal":3,"rows":10,"sidx":null,"sord":"asc","total":1,"trackingNr":null,"truckId":"174225","truckShipmentComponent":{}}
First of all there are small errors in the JSON data which you posted. It contains no commas after "trackingNr":"1Z1484366620874746" and "trackingNr":"1Z1484366620874764". I hope that it's only cut&paste error during preparing the data for the question. In any way it would be more safe to include loadError callback (see the answer) in case of loading errors.
Your main error seems to me are inside of beforeProcessing callback. The data parameter of the callback contains the server response. The array of items you have inside of data.records, but you use var rows = data.rows, ... instead. The line should be fixed to var rows = data.records, ....
One asked you in the comment to prepare JSFiddle demo which demonstrates the problem and you had problems to prepare it because of usage datatype: "json". On the other side JSFiddle do provides you possibility to implement demos in the case. One can use Echo service. In case of jqGrid one needs just use mtype: "POST" and url: "/echo/json/". To inform echo service which data you want to have one need just send JSON encoded data in json parameter. So the fill looks like
// the data which we want to receive back
var serverResponse = {
"page":1,
...
};
$("#gridId").jqGrid({
url: "/echo/json/", // use JSFiddle echo service
postData: {
json: JSON.stringify(serverResponse) // needed for JSFiddle echo service
},
datatype: "json",
mtype: "POST", // needed for JSFiddle echo service
...
});
The working JSFiddle demo you can find here: http://jsfiddle.net/OlegKi/ntfw57zm/. I makes some small additional optimization of your code.
I hope the example could help other people to post his questions with JSFiddle demos.

How to make only the clicked cell editable instead of all the editable cells in the row clicked - using jqgrid?

At present I'm getting all the cells (with editable:true) in the row editable in which i clicked and not only the clicked the cell. The table is similar to the table in this link: http://www.ok-soft-gmbh.com/jqGrid/ClientsideEditing4.htm. I've gone through the link: http://www.trirand.com/jqgridwiki/doku.php?id=wiki:cell_editing, but didn't help (may be due to my fault in the way i tried) and also tried the answers given in stackoverflow related questions (used the attributes: cellEdit: true, cellsubmit: "clientArray").
Please help me using the above link as reference http://www.ok-soft-gmbh.com/jqGrid/ClientsideEditing4.htm (I think mainly the "onSelectRow", "ondblClickRow" functions need to be updated. i tried onSelectCell etc. but failed! ).
Thanks in advance.
If you need to use cell editing you have to include cellEdit: true in jqGrid definition. If you use local datatype then you should use cellsubmit: "clientArray" additionally. If you want to save data on the remote source you have to implement editing in your server code and specify cellurl option of jqGrid. The documentation describes what jqGrid send to the server on saving of cell.
I'm currently working on an Angular 2 app with Typescript, and I had a different need where I wanted to be able to click a row in the grid, but only have one cell editable. I didn't like the user experience where the user had to click the actual cell to edit it. Instead, clicking the row highlights the row and then makes the one cell editable. Here's a screenshot:
The trick was that I needed to set cellEdit to false on the grid and then set the individual column editable to true when declaring my column model array, and write a change event for the editoptions of the column. I also had to write code for the the onSelectRow event of the grid, to keep track of the current row selected and to restore the previous row selected. A snippet of the Typescript code is below:
private generateGrid() {
let colNames = ['id', 'Name', 'Total', 'Assigned', 'Distributed', 'Remaining', 'Total', 'Assigned', 'Remaining', 'Expiration'];
let self = this;
// declare variable to hold Id of last row selected in the grid
let lastRowId;
let colModel = [
{ name: 'id', key: true, hidden: true },
{ name: 'name' },
{ name: 'purchasedTotalCount', width: 35, align: 'center' },
{ name: 'purchasedAssignedCount', width: 35, align: 'center' },
{ name: 'purchasedDistributedCount', width: 35, align: 'center' },
{ name: 'purchasedRemainingCount', width: 35, align: 'center' },
// receivedTotalCount is the only editable cell;
// the custom change event works in conjunction with the onSelectRow event
// to get row editing to work, but only for this one cell as being editable;
// also note that cellEdit is set to false on the entire grid, otherwise it would
// require that the individual cell is selected in order to edit it, and not just
// anywhere on the row, which is the better user experience
{ name: 'receivedTotalCount',
width: 35,
align: 'center',
editable: true,
edittype: 'text',
editoptions: {
dataEvents: [
{
type: 'change', fn: function(e) {
//TODO: don't allow decimal numbers, or just round down
let count = parseInt(this.value);
if (isNaN(count) || count < 0 || count > 1000) {
alert('Value must be a whole number between 0 and 1000.');
} else {
self.updateLicenses(parseInt(lastRowId), count);
}
}
},
]
}
},
{ name: 'receivedAssignedCount', width: 35, align: 'center' },
{ name: 'receivedRemainingCount', width: 35, align: 'center' },
{ name: 'expirationDate', width: 45, align: 'center', formatter: 'date' }
];
jQuery('#licenseManagerGrid').jqGrid({
data: this.childTenants,
datatype: 'local',
colNames: colNames,
colModel: colModel,
altRows: true,
rowNum: 25,
rowList: [25, 50, 100],
width: 1200,
height: '100%',
viewrecords: true,
emptyrecords: '',
ignoreCase: true,
cellEdit: false, // must be false in order for row select with cell edit to work properly
cellsubmit: 'clientArray',
cellurl: 'clientArray',
editurl: 'clientArray',
pager: '#licenseManagerGridPager',
jsonReader: {
id: 'id',
repeatitems: false
},
// make the selected row editable and restore the previously-selected row back to what it was
onSelectRow: function(rowid, status) {
if (lastRowId === undefined) {
lastRowId = rowid;
}
else {
jQuery('#licenseManagerGrid').restoreRow(lastRowId);
lastRowId = rowid;
}
jQuery('#licenseManagerGrid').editRow(rowid, false);
},
});
}
Additionally, I wanted the escape key to allow the user to abort changes to the cell and then restore the cell to its previous state. This was accomplished with the following Angular 2 code in Typescript:
#Component({
selector: 'license-manager',
template: template,
styles: [style],
host: {
'(document:keydown)': 'handleKeyboardEvents($event)'
}
})
// handle keypress so a row can be restored if user presses Escape
private handleKeyboardEvents(event: KeyboardEvent) {
if (event.keyCode === 27) {
let selRow = jQuery('#licenseManagerGrid').jqGrid('getGridParam', 'selrow');
if (selRow) {
jQuery('#licenseManagerGrid').restoreRow(selRow);
}
}
}

jqGrid, couldn't get showlink formatter working

Hi I am trying to get showlink formatter working by following this document from trirand.
What I want to achieve is a hyperlink I can click for a edit view to update/edit records. But for some reason, the column are empty where I want show a hyperlink.
Here is my code snippets, and link is the last column:
<script type="text/javascript">
$(document).ready(function () {
$("#grid_products").jqGrid({
jsonReader: {
repeatitems: false,
id: 'Guid'
},
url: '/Product/jqgridJSON/',
datatype: 'json',
mtype: 'GET',
colNames: ['ProductCode', 'ProductDescription', 'DefaultSellPrice', 'LastCost', 'Edit'],
colModel: [
{ name: 'ProductCode', index: 'Productcode' },
{ name: 'ProductDescription', index: 'ProductDescription' },
{ name: 'DefaultSellPrice', formatter: 'currency', index: 'DefaultSellPrice' },
{ name: 'LastCost', formatter: 'currency', index: 'LastCost' },
{ name: 'MyLink',
edittype: 'select',
formatter: 'showlink',
formatoptions: { baseLinkUrl: '/Product/Update/', idName: 'Guid' }
},
],
pager: '#pager',
rowNum: 10,
rowList: [20, 50, 100, 200],
sortname: 'ProductCode',
sortorder: 'asc',
viewrecords: true,
width: 'auto',
height: 'auto',
caption: 'Products'
}).navGrid('#pager', { edit: true, add: false, del: false });
});
</script>
#{
ViewBag.Title = "JSONGrid";
}
<h2>JSONGrid</h2>
<table id="grid_products"></table>
<div id="pager"></div>
The formatter from jqGrid is working for currency, but for some reason, it just didn't shown for hyperlink.
Update:
Got it working by using custom formatter.
...
{ name: 'MyLink',
formatter: myLinkFormatter,
},
...
function myLinkFormatter (cellvalue, options, rowObjcet) {
return 'Edit this product';
}
I suppose that you fill no value in JSON input for the 'MyLink' column. Because of this the hyperlink is empty. If you want to place the link with any fixed text in column I would recommend you to use custom formatter. See the recent answer for an example.
One more possible solution way is to use formatter: 'showlink' and include jsonmap: function() { return "Edit"; } to the 'MyLink' column definition. In the case you will not need to include in the JSON data "MyLink":"Edit" for every row of data. It's important to understand that the trick works only in case of usage jsonReader: {repeatitems: false} (so it should work for your grid).
If you have another problem you should include in the text of your question the JSON data which you use.
Some small remarks to your current code:
the usage of edittype: 'select' together with formatter: 'showlink' has no sense. You should remove it if you will do use formatter: 'showlink'.
the parameter height: 'atuo' should be height: 'auto'.
pager: $('#pager') is better to replace to pager: '#pager'. If you use pager: $('#pager'), the jqGrid will replace it internally to pager: '#pager' and the object $('#pager') will be discarded.
If you use jsonReader: { id: 'Guid'} and you don't plan to show the guids to the user you can remove the 'Guid' column from the grid. The id (the Guid in your case) will be used to assign ids of <tr> elements (table rows) of the grid. So you don't need to hold the same information twice

Categories