jqGrid Inline edit: Append custom element next to dropdown - javascript

I have the following grid which contains data from a local array (which I save with my own custom call):
var datagrid = [
{name:"Id",description:"description",entityid:"12",amount:"100"},
{name:"Id2",description:"description",entityid:"17",amount:"200"}
];
$grid = $("#grid1").jqGrid({
datatype: "local",
data: datagrid,
height: "auto",
autowidth: true,
shrinkToFit: false,
colNames:['Name','Description', 'Entity', 'Amount', ''],
colModel:[
{index: 'name', name: 'name', editable: true, edittype: 'text'},
{index: 'description', name: 'description', editable: true, edittype: 'text'},
{index: 'entityid', name: 'entityid', editable: true, edittype: 'select', formatter: 'select', edittype: 'select', editoptions:
{
dataUrl: 'url/to/drop/down/data',
buildSelect: function(data)
{
return buildSelectFromJson(data, 'oid', 'oname');
}
}
},
{index: 'amount', name: 'amount', editable: true, edittype: 'text'},
{name:'act', index:'act', sortable:false, width: "140px"}
],
onSelectRow: function(rowid){
rowSelected('grid1', rowid);
},
rowNum: 500,
editurl: "clientArray",
caption: "Details",
ajaxSelectOptions: {contentType: "application/json", dataType: 'json'}
});
$grid.jqGrid('hideCol',['act']);
Next to the "entityid" drop down I want to add a button to show a popup to enter a new entity. I want the new entity to be loaded in the drop-down after the popup closes.
Previously I used editoptions: {value: getValueFunction} but I read some advice in stack overflow which advised against it and anyway I could not load the new entity in the drop-down after the popup closed. But I was able to add the button this way:
function rowSelected(gridid, rowid){
var $grid = $("#" + gridid);
var rowData = $grid.jqGrid('getRowData', rowid);
$grid.jqGrid('showCol',["act"]);
var oneditfunction = function(){
var button = '<input id="newFieldRange" type="button" value="+"></input>';
$grid.find("select").parent().append(button);
$("#newEntity").on('click', function () {
newEntity(gridid, rowid);
});
};
$grid.jqGrid('editRow', rowid, {oneditfunc: oneditfunction});
}
Using the same code for rowSelected function and the code I showed above for the grid, the button is not added. The drop-down is filled with data successfully.
I have the following questions:
1) How can I add a custom button to "entity" cell? Is this not advised? The columns and data I show are not the real data for simplicity reasons. Due to some restrictions, it is not possible to add another column next to the drop-down (we use 'act' column for "Save" and "Cancel" buttons). I would like to add the button in the same cell as the drop-down. Unless there are alternative solutions.
2) How can I force the drop-down to reload after I close the "New entity" popup? I couldn't find anything in the jqGrid wiki.
EDIT: I was able to add the button using onsuccessfunc of jQGrid's editRow. But I am forced to use "select" jqgrid selector without specifying an id, because the and elements do not have any ids. I might need to add another dropdown which would cause issues. Am I missing something?
Thanks in advance for any responses.

Related

jqGrid get cell data into delOptions property

I have a colModel column that when a user presses the button, it will delete the row. However, I need this to go to the server (which is does) and delete it from the database using the row's ID.
This is the code that does it
colModel: [
...
{ name: 'id', index: 'Id', width: 70, hidden: true, editable: true,
{
name: 'actions', index: 'actions', width: 20, sortable: false, editable: false, formatter: imageFormat,
formatoptions: {
keys: true,
editbutton: false,
// I need to pass id from above into the server....this is what should happen here
delOptions: { url: Controller + 'Action?paramenter=' + id}
}
},
],
The problem is that I need to get the value of the id column and pass it in the parameter like above.
How can this be done?
Thanks
Ok I didnt use delOptions I used the .jqGrid('delGridRow') method inside the onSelectRow property,
and to get the id I used..
var myGrid = $('#grid'),
selRowId = myGrid.jqGrid('getGridParam', 'selrow'),
celValue = myGrid.jqGrid('getCell', selRowId, 'name');
So therefore...
jQuery("#resume").jqGrid('delGridRow', id, { height: 480, width: 400, closeAfterAdd: true, closeAfterEdit: true, recreateForm: true,url: Controller + 'Action?paramenter=' + celValue });
with the loadComplete() method, you can do like this:
$(table).find(".ui-inline-del").each(function() {
var delDivBtn = $(this);
var id_reg = /(\w+)([_]{1})(\w+$)/;
// remove the delete event
$(delDivBtn).removeAttr("onclick");
// add new click event
$(delDivBtn).click(function() {
var rowid = delDivBtn.attr("id").replace(id_reg, '$3');
alert(rowid);
});
});

jquery & ajax _ call data from database

I'm trying to create a dynamic select box which is using jqgrid-plugin.
I want to call data from my database(oracle) and put it in the select box so that the called data would be showed within select box. I'm not an expert at jquery and ajax.
I've tried to edit the 'edittype' and 'edditoptions' which are attributes of jqgrid colModel[] but it wasn't proper situation.
How can i call data from database to use ajax.
Here is my code below related to jgGrid columns.
jQuery(function($) {
jQuery(grid_selector).jqGrid({
url: '/jqGrid/merchantEstablishmentList',
datatype: 'json',
height: 'auto', autowidth: true,
colNames:
[
'Establishment ID',
'Establish Name',
'Corporation ID'
],
colModel:
[
{name:'ESTABLISHMENT_ID',index:'ESTABLISHMENT_ID', editable:true, sortable:false,search: false},
{name:'ESTABLISHMENT_NAME',index:'ESTABLISHMENT_NAME', editable:true, sortable:false,search: false},
{name:'CORPORATE_ID',index:'CORPORATE_ID',editable:true,edittype:"select", editoptions:{value : },editrules:{required:true},sortable:false,search: false},
],

Want to create JQgrid with inline add,edit,save without any buttons [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Below is my requirement:
Initially JQgrid should be Empty
On click of Jqgrid an new row has to be added with auto ID
On lost focus of row data should be saved to DB
On click of row user should be able to edit it and on lost focus data should be saved to DB
var lastsel;
jQuery("#list").jqGrid({
url: "/TransactionType/GetGridData/",
datatype: 'json',
mtype: 'GET',
height: "300",
colNames: ['Customer ID', 'Contact Name', 'Address', 'City', 'Postal Code'],
colModel: [
{ name: 'CustomerID', index: 'CustomerID', width: 100, align: 'left' },
{ name: 'ContactName', index: 'ContactName', width: 150, align: 'left', editable: true },
{ name: 'Address', index: 'Address', width: 300, align: 'left', editable: true },
{ name: 'City', index: 'City', width: 150, align: 'left', editable: true },
{ name: 'PostalCode', index: 'PostalCode', width: 100, align: 'left', editable: true }
],
pager: jQuery('#pager'),
rowNum: 10,
rowList: [1, 3, 5, 10, 20, 30, 40, 50],
recordpos: 'right',
viewrecords: true,
sortorder: "desc",
sortname: "CustomerID",
sorttype: "integer",
multiselect: false,
caption: "Manipulating JSON Data",
emptyrecords: "No records found.",
loadtext: "Loading...",
loadonce: true,
pgtext: "Page {0} of {1}",
jsonReader: {
repeatitems: true,
cell: "cell"
},
onSelectRow: function (id) {
if (id) {
if (id !== lastsel) {
jQuery('#list').jqGrid('restoreRow', lastsel);
jQuery('#list').jqGrid('editRow', id, true);
lastsel = id;
} else {
jQuery('#list').jqGrid('restoreRow', lastsel);
lastsel = "";
debugger;
var rows = jQuery("#list").jqGrid('getRowData');
var paras = new Array();
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
paras.push($.param(row));
}
var rids = $('#list').jqGrid('getDataIDs');
var n = rids.length;
var nth_row_id = rids[n - 1];
jQuery("#list").addRow(n + 1, parameters = {
edit: true,
editicon: "ui-icon-pencil",
add: true,
addicon: "ui-icon-plus",
save: true,
saveicon: "ui-icon-disk",
cancel: true,
cancelicon: "ui-icon-cancel",
addParams: { useFormatter: false },
editParams: {}
});
}
}
},
editurl: "/TransactionType/GetTotalCount",
});
This is my Jqgrid where i'm able to add the row but not with auto generated id and I'm not able to call the controller method after lost focus of row or Enter key.
jqGrid includes inlineNav method which allows to add to the navigator bar (created by navGrid called typically with add: false, edit: false option, see the answer) Add, Edit, Save and Cancel buttons. If the user click on one from the button the corresponding inline editing method will be called. One can use editParams and addParams.addRowParams to specify any additional options of inline editing methods (see here for example).
You current code use addRow directly. The second option (parameters =) contains wrong syntax. If you would need to generate unique id I would recommend you to use $.jgrid.randId() instead of usage n + 1. The first, and the only, parameter of addRow is object with options. If you use adRow directly you can use rowID option to specify the id of new added row. If no rowID option is specified jqGrid uses $.jgrid.randId() automatically to generate unique rowid of new row.
The ids of all inline editing buttons are set based on the id of the grid and a suffix: "_iladd", "_iledit", "_ilsave", "_ilcancel". For example is the grid have id="list" then the id of Save button will be "list_ilsave". If required you can disable any button by addressing it by its id (for example $("#list_ilsave").removeClass('ui-state-disabled'); - enable Save button and $("#list_ilsave").addClass('ui-state-disabled'); - disable it). In the same way you can use jQuery.click to simulate click on any button. For example $("#list_ilsave").click(); will simulate clicking on the Save button.
If the user clicks on Add button the new row (<tr>) will get additional class "jqgrid-new-row". You can use the fact to find rows added by addRow.
You can use editoptions.dataEvents to register blur or focusout. The answer and the answer could provide some code fragmants which could help you.
It could be important to refresh the ids of the grid with the values generated in DB after successful saving. There are many ways to implement this. One of the most easy way would be to reload the grid after successful saving the row. See the code from the answer. Another way will be to return the new id from the web method specified by editurl ("/TransactionType/GetTotalCount" in your code). Using aftersavefunc callback you can get the response of editurl and makes modification of the id of in the grid. See relatively long code of aftersavefunc in the answer as an example.

Get the key value of the row of whose cusstom button has been clicked

I found myself in need of what i guess should be a trivial requirement. i have a jqGrid in which i have added a custom button in each row. now i am able to associate a client side click event with it but i want to know the key value (Id) in my case of the row whose custom button was clicked, so that i can proceed with this id and do whatever i want to do.
My code for jqGrid is as below
jQuery("#JQGrid").jqGrid({
url: 'http://localhost:55423/JQGrid/JQGridHandler.ashx',
datatype: "json",
colNames: ['', 'Id', 'First Name', 'Created Date', 'Member Price', 'Non Member Price', 'Complete', 'customButton'],
colModel: [
{ name: '', index: '', width: 20, formatter: "checkbox", formatoptions: { disabled: false} },
{ name: 'Id', index: 'Id', width: 20, stype: 'text', sortable: true, key: true },
{ name: 'FirstName', index: 'FirstName', width: 120, stype: 'text', sortable: true },
{ name: 'CreatedDate', index: 'CreatedDate', width: 120, editable: true, sortable: true, hidden: true, editrules: { edithidden: true} },
{ name: 'MemberPrice', index: 'MemberPrice', width: 120, editable: true, sortable: true },
{ name: 'NonMemberPrice', index: 'NonMemberPrice', width: 120, align: "right", editable: true, sortable: true },
{ name: 'Complete', index: 'Complete', width: 60, align: "right", editable: true, sortable: true },
{ name: 'customButton', index: 'customButton', width: 60, align: "right" }
],
rowNum: 10,
loadonce: true,
rowList: [10, 20, 30],
pager: '#jQGridPager',
sortname: 'Id',
viewrecords: true,
sortorder: 'desc',
caption: "List Event Details",
gridComplete: function () {
jQuery(".jqgrow td input", "#JQGrid").click(function () {
//alert(options.rowId);
alert("Capture this event as required");
});
}
});
jQuery('#JQGrid').jqGrid('navGrid', '#jQGridPager',
{
edit: true,
add: true,
del: true,
search: true,
searchtext: "Search",
addtext: "Add",
edittext: "Edit",
deltext:"Delete"
},
{/*EDIT EVENTS AND PROPERTIES GOES HERE*/ },
{/*ADD EVENTS AND PROPERTIES GOES HERE*/},
{/*DELETE EVENTS AND PROPERTIES GOES HERE*/},
{/*SEARCH EVENTS AND PROPERTIES GOES HERE*/}
);
Help or any pointers would be much appreciated.
The main solution of your problem in the following: you need include parameter, for example e, in the callback of click handle. The parameter has Event object type which contain target property. Alternatively you can use this in the most cases. Having e.target you can goes to the closest parent <tr> element. It's id is the value which you need:
jQuery(this).find(".jqgrow td input").click(function (e) {
var rowid = $(e.target).closest("tr").attr("id");
alert(rowid);
});
Additionally you should make some other modifications in your code to fix some bugs. The usage of
name: '', index: ''
is wrong in colModel. You should specify any non-empty unique name. For example name: 'mycheck'.
Next I recommend you to remove all index properties from colModel. If you use loadonce: true you have to use index properties with the same values as the corresponding name values. If you don't specify any index properties you will have smaller and better readable code. The corresponding values of index properties will be copied by jqGrid internally from the corresponding name values. In the same way you can remove properties like stype: 'text', sortable: true which values are default values (see Default column of the documentation)
The next problem is that you include probably HTML data in the JSON response from the server. (One can't see any formatter for customButton for example). It's not good. In the way you can have problems if the texts of the grid contains special HTML symbols. I find better to use pure data in JSON response from the server. One can use formatters, custom formatters etc on the client side. In the case one can use autoencode: true option of jqGrid which make HTML encoding of all texts displayed in the grid. In the way you will have more safe code which will don't allow any injection (for example no including of JavaScript code during editing of data).
Next remark: I don't recommend you to use gridComplete. The usage of loadComplete is better. See my old answer about the subject.
The last important remark. To handle click events on the buttons placed inside of grid one don't need to bind separate click handle to every button. Instead of that one can use one beforeSelectRow or onCellSelect callback. The answer and this one describe this. The answers use <a> in custom formatter, but <input> works exactly in the same way.
Another approach that can be used to retrieve the id of the row for which the custom button is clicked is by adding formatter to your custom button cloumn
{ name: 'customButton', index: 'customButton', width: 60, align: "right",
formatter: function ( cellvalue, options, rowObject ) {
return "<input type='button' class='custom-button' id='custom"+ rowObject.id +"'/>";
}
}
Now every button has the row id
$('input[id^="custom"]').click(function() {
var id = this.attr('id').replace("custom", ""); // required row ID
});

jqGrid SetCell and SaveCell blanking out the cell after closing a modal dialog

I have a cell-editable jqgrid with a column that has an edittype of 'button'. When the cell is clicked, the button appears. when the button is clicked, a modal dialog appears allowing the user to select a value from a grid. This is all working fine.
When the user clicks the 'OK' button on the modal dialog after picking a value from the grid, I'd like to set the cell value with the value selected by the user and save the cell.
Instead of setting and saving the cell value, the cell is blanked out. Not sure why.
Here is the relevant jqGrid / modal dialog code:
// global variables
base.selectedCode = null;
base.liaGridSelectedId = null;
base.liaGridSelectedICol = null;
base.liaGridSelectedIRow = null;
$("#liaGrid").jqGrid({
datatype: "local",
data: base.liaGridData,
cellEdit: true,
cellsubmit: 'clientArray',
height: 140,
colNames: ['ID', 'Class Code', 'State', 'Location Type'],
colModel: [
{ name: 'id', index: 'id', width: 90, sorttype: "int", editable: false, hidden: true },
{ name: 'ClassCode', index: 'ClassCode', width: 90, sortable: false, editable: true, edittype: "button",
editoptions: {
dataEvents: [{
type: 'click',
fn: function (e) {
e.preventDefault();
var rowid = $('#liaGrid').jqGrid('getGridParam', 'selrow');
base.liaGridSelectedId = parseInt(rowid);
$('#class-dialog').dialog('option', { width: 100, height: 200, position: 'center', title: 'Pick a Class' });
$('#class-dialog').dialog('open');
return true;
}
}]
}
},
{ name: 'LocationType', index: 'LocationType', width: 90, sortable: false, editable: true, edittype: "select", editoptions: { value: "0:;1:Rural;2:Suburban;3:Urban"} }
],
caption: "Liability Model",
beforeEditCell: function (rowid, cellname, value, iRow, iCol) {
base.liaGridSelectedICol = iCol;
base.liaGridSelectedIRow = iRow;
}
});
var infoDialog = $('#class-dialog').dialog({
autoOpen: false,
modal: true,
show: 'fade',
hide: 'fade',
resizable: true,
buttons: {
"Ok": function () {
if (base.selectedCode != null) {
$("#liaGrid").jqGrid('setCell', base.liaGridSelectedId, 'ClassCode', base.selectedCode);
$("#liaGrid").jqGrid('saveCell', base.liaGridSelectedIRow, base.liaGridSelectedICol);
$(this).dialog("close");
}
},
"Cancel": function () {
$(this).dialog("close");
}
}
});
As seen above, I'm attempting to use jqGrid('setCell') and jqGrid('saveCell') to update and save the contents of the cell. Not sure why this fails to succeed.
I got this to work in case anyone encounters a similar issue. I had to add the afterSaveCell handler to the grid:
afterSaveCell: function (rowid, name, val, iRow, iCol) {
if (base.liaGridSelectedICol == 1) {
$("#liaGrid").jqGrid('setRowData', rowid, { ClassCode: base.selectedCode });
}
}
FYI - base.selectedCode is set in the modal.
Odd thing, this only worked after calling the setCell and saveCell methods. Without these unsuccessful calls to set and save at the cell level, the above handler was not called.
If someone has a more appropriate approach to solving this problem I'd like to hear it.
Thanks

Categories

Resources