DataTables gives warning if there is an empty cell - javascript

DataTables alerts me if there is an empty cell in my table. Here is the warning:
Requested unknown parameter 'Description' for row 1.
My code is here:
var columns = [
{
mDataProp: 'Description',
sTitle: 'Description'
},
//
// other columns
//
];
var dt = $('#myDataTable').dataTable({
sAjaxSource: '/JobScheduler/GetJobs',
bServerSide: true,
fnServerData: function (sSource, aoData, fnCallback) {
$(aoData).each(function(i, o){
var params = o.name.split('_');
if (params[0] == 'mDataProp')
{
var value = $.grep(aoData, function(e){ return e.name == "sSearch_" + params[1]; })[0].value;
if (value != "")
{
aoData.push({ name: o.value, value: value });
}
}
});
$.getJSON(sSource, aoData, function (data) {
if (isSuccess(data)) {
fnCallback(data.message);
} else {
showMessage(data);
}
});
},
bProcessing: true,
sDom: 'T<"new">Rrlptip',
fnRowCallback: function (nRow, aData) {
nRow.setAttribute('id', aData['JobId']);
},
aoColumns: columns
})
What should I do to prevent this warning? Thanks in advance.

Check your columns and add a defaultContent option for the one(s) causing you issues.
Something like this:
...
{
mDataProp: 'YourData',
sTitle: 'YourDescription',
sDefaultContent: ''
},
...

Related

Datatable custom filtering with Server Side with Editor

I am having some trouble integrating some custom functionalities with Datatable and Datatable Editor at the same time.
Without server-side processing my current functionalities works perfectly but I want to be able to implement server-side filtering with Editor.
With server-side filtering these work:
1.Pagination
2.Global Search
3.Sorting
4.Row reorder
5.Dynamic Page length
With server-side filtering these don't work:
1.Custom column input filtering
2.Custom footer select filtering
My serverside script for Datatable and Editor:
Editor::inst($db, 'article_categories')
->fields(
Field::inst('article_categories.id')->validator('Validate::numeric'),
Field::inst('article_categories.name')->validator('Validate::notEmpty'),
Field::inst('article_categories.description'),
Field::inst('article_categories.rowOrder')->validator('Validate::numeric')
)
->on('preCreate', function ($editor, $values) {
if (!$values['article_categories']['rowOrder']) {
$next = $editor->db()->sql('select IFNULL(MAX(rowOrder)+1, 1) as next FROM article_categories')->fetch();
$editor->field('article_categories.rowOrder')->setValue($next['next']);
} else {
$editor->db()
->query('update', 'article_categories')
->set('rowOrder', 'rowOrder+1', false)
->where('rowOrder', $values['article_categories']['rowOrder'], '>=')
->exec();
}
})
->on('preRemove', function ($editor, $id, $values) {
$order = $editor->db()
->select('article_categories', 'rowOrder', array('id' => $id))
->fetch();
$editor->db()
->query('update', 'article_categories')
->set('rowOrder', 'rowOrder-1', false)
->where('rowOrder', $order['rowOrder'], '>')
->exec();
})
->process($request->all())
->json();
My client-side script:
Default config:
jQuery(function () {
$.extend(true, $.fn.dataTable.defaults, {
serverSide: true,
fixedHeader: true,
searchDelay: 800,
paging: true,
processing: true,
pageLength: 10,
info: true,
dom: "Blfrtip",
select: true,
responsive: true,
lengthMenu: [
[10, 25, 50, -1],
[10, 25, 50, "All"],
],
});
});
Datatable and Editor setup:
var editor;
jQuery(function () {
//Editor
editor = new $.fn.dataTable.Editor({
table: "#article-category",
ajax: {
url: "article-categories",
type: "POST",
},
fields: [
{
label: "Order:",
name: "article_categories.rowOrder",
type: "hidden",
fieldInfo:
"This field can only be edited via click and drag row reordering.",
},
{
label: "FAQ Category Name:",
name: "article_categories.name",
},
{
label: "Description (optional):",
name: "article_categories.description",
type: "textarea",
},
],
});
//Datatable
var table = $("#article-category").DataTable({
ajax: {
url: "article-categories",
type: "POST",
},
rowReorder: {
dataSrc: "article_categories.rowOrder",
editor: editor,
},
buttons: cms.editorFormButtons(editor),
initComplete: function () {
cms.headerInputFilter("article-category", this.api(), [1, 2]);
cms.footerSelectFilter(this.api(), [1, 2]);
},
columns: [
{
data: "article_categories.rowOrder",
name: "article_categories.rowOrder",
className: "reorder no-inline",
},
{
data: "article_categories.name",
name: "article_categories.name",
},
{
data: "article_categories.description",
name: "article_categories.description",
},
],
});
//Inline Editor
cms.inlineEdit("article-category", editor);
editor
.on("postCreate postRemove", function () {
table.ajax.reload(null, false);
})
.on("initCreate", function () {
editor.field("article_categories.rowOrder").enable();
})
.on("initEdit", function () {
editor.field("article_categories.rowOrder").disable();
});
});
Custom functions:
let footerSelectFilter = function (table, columns) {
if (typeof columns != "undefined" && typeof table != "undefined") {
table.columns(columns).every(function () {
var column = this;
var select = $('<select><option value=""></option></select>')
.appendTo($(column.footer()).empty())
.on("change", function () {
var val = $.fn.dataTable.util.escapeRegex($(this).val());
column
.search(val ? "^" + val + "$" : "", true, false)
.draw();
});
column
.data()
.unique()
.sort()
.each(function (d, j) {
select.append(
'<option value="' + d + '">' + d + "</option>"
);
});
});
}
};
let headerInputFilter = function (target, table, searchableColumns) {
if (
typeof searchableColumns != "undefined" &&
typeof target != "undefined" &&
typeof table != "undefined"
) {
$("#" + target + " thead tr")
.clone(true)
.addClass("filters")
.appendTo("#" + target + " thead");
var i = 0;
var api = table;
api.columns()
.eq(0)
.each(function (colIdx) {
if (
searchableColumns.includes(
$(api.column(colIdx).header()).index()
)
) {
var cell = $(".filters th").eq(
$(api.column(colIdx).header()).index()
);
var title = $(cell).text();
$(cell).html(
'<input style="width:100% !important" type="text" placeholder="' +
title +
'" />'
);
$(
"input",
$(".filters th").eq(
$(api.column(colIdx).header()).index()
)
)
.off("keyup change")
.on("keyup change", function (e) {
e.stopPropagation();
$(this).attr("title", $(this).val());
var regexr = "({search})";
var cursorPosition = this.selectionStart;
api.column(colIdx)
.search(
this.value != ""
? regexr.replace(
"{search}",
"(((" + this.value + ")))"
)
: "",
this.value != "",
this.value == ""
)
.draw();
$(this)
.focus()[0]
.setSelectionRange(
cursorPosition,
cursorPosition
);
});
} else {
return true;
}
});
}
};
let editorFormButtons = function (editor) {
if (typeof editor != "undefined") {
return [
{
extend: "create",
editor: editor,
formButtons: [
{
label: "Save",
fn: function () {
var that = this;
this.submit(function () {
that.close();
});
},
},
],
},
{
extend: "edit",
text: "Edit",
editor: editor,
formButtons: [
{
label: "Save & close",
fn: function () {
var that = this;
this.submit(function () {
that.close();
});
},
},
{
label: "Update",
fn: function () {
this.submit(function () {
editor.edit(
table.rows({ selected: true }).indexes()
);
});
},
},
],
},
{
extend: "remove",
editor: editor,
formButtons: [
{
label: "Delete",
fn: function () {
var that = this;
this.submit(function () {
that.close();
});
},
},
],
},
];
}
};
let inlineEdit = function (target, editor) {
if (typeof target != "undefined" && typeof editor != "undefined") {
$("#" + target + "").on(
"click",
"tbody td:not(.no-inline)",
function (e) {
if (
$(this).hasClass("editor-edit") ||
$(this).hasClass("control") ||
$(this).hasClass("select-checkbox") ||
$(this).hasClass("dataTables_empty")
) {
return;
}
editor.inline(this, {
submit: "allIfChanged",
});
}
);
}
};
module.exports = {
headerInputFilter,
footerSelectFilter,
editorFormButtons,
inlineEdit,
};
When I set server-side to false the custom functionalities I need works perfectly but I need these with server-side processing as it will significantly improve overall performance . I would appreciate any help and suggestion.
Regards,
Shovon Choudhury

Datatables rows.add error - Warning: Requested unknown

I have been working with datatables for a couple of weeks and I have this custom datatables that I'm identifying by class (tableIdentifyClass):
var handleDataTable = function () {
if ($("." + tableIdentifyClass).length) {
table = $("." + tableIdentifyClass).DataTable({
aaData: dataForTable,
aoColumns: [
{ mData: "IsDefault", title: "" },
{ mData: "Name", title: "Name" },
{ mData: "Icon", title: "Icon" },
{ mData: "IsDefault", title: "" }],
"order": [[1, "asc"]],
"bAutoWidth": false,
"lengthChange": false,
"columnDefs": [{
"targets": 0,
"render": function (data, type, full, meta) {
if (type === 'display') {
if (!data)
return '<span class="fa-xs"><i class="fa fa-edit" style="font-size:125%" onclick:""></i></span>';
else return '<span></span>';
}
return (isNaN(data)) ? -1 : +data;
}
},
{
"targets": 2,
"render": function (data, type, full, meta) {
if (type === 'display') {
if (data != '')
return '<span class="fa-xs"><i class="fa ' + data + '" style="font-size:125%"></i></span>';
else return '<span>-</span>';
}
return (isNaN(data)) ? -1 : +data;
}
},
{
"targets": 3,
"render": function (data, type, full, meta) {
if (type === 'display') {
if (!data)
return '<a class="fa-xs"><i class="fa fa-times" style="font-size: 125%; color: red;" onclick="deletePrefLocally(' + full.UId + ',' + full.Id + ',\'' + tableIdentifyClass + '\')"></i></a>';
else return '<span></span>';
}
return (isNaN(data)) ? -1 : +data;
}
}]
});
}
}
The data for the table (dataForTable):
[ { "Icon": "fa-exclamation-circle", "IsDefault": true, "Name": "Nixon", "UId": 1 },
{ "Icon": "fa-exclamation-circle", "IsDefault": false, "Name": "Tiger", "UId": 2 }]
I'm trying to delete the second row by calling function deletePrefLocally
function deletePrefLocally(uId, deletedId, tableIdentifyClass) {
var crtUsage = dataForTable; //same items as the table
var inItems = crtUsage.filter(function (elem) {
return elem.Id === deletedId; // find the item with the same id
})[0];
var found = crtUsage.indexOf(inItems);
if (found != -1) crtUsage.splice(found, 1);
table = $("." + tableIdentifyClass);
datatable = table.DataTable();
datatable.clear();
datatable.rows.add(crtUsage).draw();
}
My problem is that the last row datatable.rows.add(crtUsage).draw(); pops-up a message: DataTables warning: - Request unknows parameter '0' for row 0, column 0. For more information about this error, please see http://datatables.net/tn/4
Why is not applying the new content? Why after closing the error box I have two search areas and paging and all the values are null? What am I doing wrong?
You've defined "IsDefault" twice in your column list.
aoColumns: [
{ mData: "IsDefault", title: "" },
{ mData: "Name", title: "Name" },
{ mData: "Icon", title: "Icon" },
{ mData: "IsDefault", title: "" }],
I suspect you meant to have "UId" for the last one, as that is included in the data.
Found the reason... After all the page was loaded I've checked if based on tableIdentifyClass I'll receive true after calling $.fn.DataTable.isDataTable( '.' + tableIdentifyClass) but it was false. When calling datatable = table.DataTable(); I was creating a datatable inside the existing one, duplicate search area and paging :( I've tried to save all the "tables" after initialization inside an global array and search for it in order to add the new rows. Perhaps this is not the best solution but it worked for me.

Call function after DataTable is filtered

I have DataTable filled with js-switches, here's the code:
$('#bandsTable').DataTable({
"processing": true,
"serverSide": true,
"ajax": {
'type': 'GET',
'url': 'myUrl',
'data': function (d) {
d._token = Laravel.csrfToken;
}
},
columns: [
{
title: "Number",
data: "number"
},
{
title: "Privileged",
data: "privileged"
}
],
columnDefs: [
{
render: function (data) {
var checked = data ? 'checked' : '';
return '' +
'<input type="checkbox" class="js-switch" id="schedule_deactivation" ' +
checked + ' data-switchery="false" style="display: none;"> \n';
},
targets: 1
}
],
order: [[0, 'asc']],
fnRowCallback: function( nRow, aData, iDisplayIndex ) {
nRow.className = "band-row";
nRow.setAttribute("data-band", aData.number);
return nRow;
},
responsive: true
});
When I filter result's they're displayed correctly, but I don't see checkboxes generated, I can type JS from the console and it works when I type:
var elems = Array.prototype.slice.call(document.querySelectorAll('.js-switch'));
elems.forEach(function (html) {
var switchery = new Switchery(html, {
color: '#26B99A',
secondaryColor: '#ff7a77'
});
});
but I don't know when I should call this code. I have no idea about DataTable lifecycle and where should I inject the code. Should it be some callback defined by DataTables or something else?
please see the documentation on the below link for more, but the code should work as follows:
$('#bandsTable').on('draw.dt', function () {
var elems = Array.prototype.slice.call(document.querySelectorAll('.js-switch'));
elems.forEach(function (html) {
var switchery = new Switchery(html, {
color: '#26B99A',
secondaryColor: '#ff7a77'
});
});
});
Link:
https://datatables.net/reference/event/

JQgrid show message before update and multiple update

I am working on JQgrid and trying to achieve some specific functionality. These functionalists are
1)inline update with message shown before update.
2)Multiple update
I tried to read jqgrid and got this code https://jsfiddle.net/OlegKi/byygepy3/11/ . Which is quite approximate to my requirement but it doesn't contain multiple update and message shown before update.
I tried to overwrite these code but maximum i reached is this https://jsfiddle.net/byygepy3/72/ but failed because multiple update only updating half of record and it doesn't show any message before updating either single row or multiple row.
code is inserting just allow me to ask question.
$(function () {
var myData = [
{ id: 10, ParameterName: "Test", ParameterValue: "" },
{ id: 20, ParameterName: "Test 1", ParameterValue: "" },
{ id: 30, ParameterName: "Test 2", ParameterValue: "" },
{ id: 40, ParameterName: "Test 2", ParameterValue: "" },
{ id: 50, ParameterName: "Test 2", ParameterValue: "" },
{ id: 60, ParameterName: "Test 2", ParameterValue: "" }
],
$grid = $("#list");
// change the text displayed on editrules: {required: true }
$.extend(true, $.jgrid.locales["en-US"].edit.msg, {
required: "No value was entered for this parameter!!!"
});
$grid.jqGrid({
datatype: "local",
data: myData,
colNames: ["", "Parameter Name", "Parameter Value"],
colModel: [
{ name: "act", template: "actions" }, // optional feature
{ name: "ParameterName" },
{ name: "ParameterValue", editable: true,
editoptions: { maxlength: 100 }, editrules: {required: true } }
],
cmTemplate: { autoResizable: true },
autoResizing: { compact: true },
pager: true,
pgbuttons: false, // disable page control like next, back button
pgtext: null, // disable pager text like 'Page 0 of 10'
viewrecords: true, // disable current view record text like 'View 1-10 of 100'
sortname: "Name",
iconSet: "fontAwesome",
caption: 'Parameters',
autowidth: true,
hidegrid: false,
inlineEditing: {
keys: true
},
singleSelectClickMode: "selectonly", // prevent unselect once selected rows
beforeSelectRow: function (rowid) {
// allow selection if saving successful
},
onSelectRow: function (rowid) {
$(this).jqGrid("editRow", rowid);
},
afterSetRow: function (options) {
var item = $(this).jqGrid("getLocalRow", options.rowid);
if (item != null) {
item.dirty = true;
}
},
navOptions: {
edit: false,
add: false,
search: false,
deltext: "Delete",
refreshtext: "Refresh"
},
inlineNavOptions: {
save: false,
savetext: "Save",
cancel: false,
restoreAfterSelect: false
},
formDeleting: {
// delete options
url: window.g_baseUrl + 'MfgTransactions_MVC/COA/Delete?',
beforeSubmit: function () {
// get value
var selRowId = $(this).jqGrid('getGridParam', 'selrow');
var parametricValue = $(this).jqGrid('getCell', selRowId, 'ParameterValue');
// check if empty
if (parametricValue === "") {
return [false, "Cannot delete: No value exists for this parameter"];
}
return [true, "Successfully deleted"];
},
delData: {
batchId: function () {
return $("#BatchId").val();
}
},
closeOnEscape: true,
closeAfterDelete: true,
width: 400,
msg: "Are you sure you want to delete the Parameter?",
afterComplete: function (response) {
if (response.responseText) {
alert("response.responseText");
}
//loadBatchListIntoGrid();
}
}
}).jqGrid('navGrid')
.jqGrid('inlineNav')
.jqGrid('navButtonAdd', {
caption: "Save Changed",
buttonicon: "fa-floppy-o",
onClickButton: function () {
var $self = $(this), i,
// savedRows array is not empty if some row is in inline editing mode
savedRows = $self.jqGrid("getGridParam", "savedRow");
for (i = 0; i < savedRows.length; i++) {
$self.jqGrid("saveRow", savedRows[i].id);
}
var localData = $(this).jqGrid("getGridParam", "data"),
dirtyData = $.grep(localData, function (item) {
return item.dirty;
});
alert(dirtyData.length > 0 ? JSON.stringify(dirtyData) : "no dirty data");
}
});
// make more place for navigator buttons be rwducing the width of the right part
var pagerIdSelector = $grid.jqGrid("getGridParam", "pager");
$(pagerIdSelector + "_right").width(100);
// make the grid responsive
$(window).bind("resize", function () {
$grid.jqGrid("setGridWidth", $grid.closest(".container-fluid").width());
}).triggerHandler("resize");
});
Free jqGrid supports a lot of callbacks, which will be used during saving the rows. You can use for example beforeSaveRow callback of inline editing, custom validation via editrules.custom callback function, beforeSelectRow and other. Additionally, your code seems to distinguish the initial empty value "" of ParameterValue column from any other values. The final code you should made yourself. I posted an example
beforeSelectRow: function (rowid) {
// allow selection if saving successful
var $self = $(this), i,
savedRows = $self.jqGrid("getGridParam", "savedRow");
for (i = 0; i < savedRows.length; i++) {
if (rowid !== savedRows[i].id) {
if (allowSaving.call(this, savedRows[i].id)) {
$self.jqGrid("saveRow", savedRows[i].id);
} else {
$self.jqGrid("restoreRow", savedRows[i].id);
}
}
}
return true;
},
with allowSaving function defined as
var allowSaving = function (rowid) {
var item = $(this).jqGrid("getRowData", rowid);
if (item.ParameterValue !== "") {
return confirm("Do you want to save \"" +
item.ParameterValue + "\" value in \"" +
item.ParameterName + "\"?");
} else {
return false;
}
};
It allows to ask the user to confirm the changes of ParameterName. Additionally the code of "Save Changed" button should be adjusted too.
See https://jsfiddle.net/OlegKi/byygepy3/74/

how do i assign value to columns in jqGird?

i am using jqGrid with CodeIgniter 2.1.0 .
The thing which is making me harassed is how to assign value to specific column on specific event
Suppose i am entering qty and rate in column value.....and when i loss focus from "rate" field.....the net amount should be calculated and displayed in amount field...
what i need to do here is to assign calculated value to amount field......but i am not getting any idea regarding how do i do it??
what i have done is given below :
var selIRow = 1;
var rowid='';
var iCol='';
$("#purchasedetailsgrid").jqGrid({
url: sitepath + 'purchase/purchase_grid',
datatype: 'json',
mtype: 'POST',
height:220,
width:500,
colNames:["","","Store Name","Item Name","Inner Pkg.","Outer Pkg.","Qty","Rate","Amount"],
colModel:[
{name: 'storeID_hidden_field', index:'storeID_hidden_field',hidden: true, editable: true,edittype: 'text',editrules: {edithidden:true}},
{name: 'itemID_hidden_field', index:'itemID_hidden_field',hidden: true, editable: true,edittype: 'text',editrules: {edithidden:true}},
{name:'store_id', index:'store_id',width:150,search:false,editable:true,editrules:{number:false,maxlength:10}},
{name:'item_id', index:'item_id',width:150,search:false,editable:true,editrules:{number:false,maxlength:10}},
{name:'inner_pkg', index:'inner_pkg',width:150,search:false,editable:true,editrules:{number:true,maxlength:5}},
{name:'outer_pkg', index:'outer_pkg',width:150,search:false,editable:true,editrules:{number:true,maxlength:5}},
{name:'qty', index:'qty',editable:true,width:85,search:false,editrules:{number:true,maxlength:5}},
{name:'rate', index:'rate',width:100,editable:true,search:false,editrules:{number:true,maxlength:10},
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
{
$('#amount').val();//here in val() i need to write the value of qty and rate field
}
}
}
]
}
},
{name:'amount', index:'amount',width:100,editable:true,search:false,editrules:{number:true,maxlength:10},
editoptions: {
dataInit: function (elem) { $(elem).focus(function () { this.select(); }) },
dataEvents: [
{
type: 'keydown',
fn: function (e) {
var key = e.charCode || e.keyCode;
if (key == 13)//enter
{
var grid = $('#purchasedetailsgrid');
//Save editing for current row
grid.jqGrid('saveRow', selIRow, false, sitepath + 'purchase/purchase_grid');
selIRow++;
//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, sitepath + 'purchase/purchase_grid');
}
}
}
]
}
}
],
pager: '#purchasedetailstoolbar',
rowNum:10,
rowList:[10,20,30],
sortname: 'inventory_id',
sortorder: 'desc',
viewrecords: true,
rownumbers: true,
gridview: true,
multiselect: false,
autoresize:true,
autowidth: true,
editurl: sitepath + 'purchase/purchase_grid',
toolbar: [true,"top"],
gridComplete: function ()
{
var grid = jQuery("#purchasedetailsgrid");
var ids = grid.jqGrid('getDataIDs');
if(ids == '')
{
grid.addRowData(selIRow, {});
grid.jqGrid('editRow', selIRow, false, sitepath + 'purchase/purchase_grid');
}
for (var i = 0; i < ids.length; i++)
{
}
},
caption: 'Purchase List',
});
jQuery("#purchasedetailsgrid").jqGrid('navGrid','#purchasedetailstoolbar',{view:false,edit:false,add:false,del:false,search: false});
jQuery("#purchasedetailsgrid").jqGrid('inlineNav','#purchasedetailstoolbar');
jQuery("#purchasedetailsgrid").jqGrid('filterToolbar',{stringResult:false,searchOnEnter : false},{autosearch: true});
var temp_purchase = $("#purchasedetailsgrid_header").html();
$("#t_purchasedetailsgrid").html(temp_purchase);
$("#refresh_purchasedetailsgrid").attr('title',"Reload Grid");
Now can anyone suggest me how will i get value from one column and assign it another?
Any suggestions will be appreciated.
Thnx in advance
You current code have many problems. For example you wrote that you need that amount will be calculated based on qty and rate, but you defined some dataEvents in 'rate' and 'amount' columns instead of 'qty' and 'rate' columns. The next problem that you use editRow method directly inside of gridComplete. So the buttons from the inlineNav toolbar will stay in the wrong status. One more problem is that you need to recompute the 'amount' based on 'qty' and 'rate' not only on the loss of focus from 'qty' and 'rate', but also on saving the values on Enter.
To make solving of above problems easier I wrote the demo which you can modify corresponds your exact requirements. The most important part of the demo you can find below:
var editingRowId = undefined,
recomputeAmount = function () {
var rate = $("#" + editingRowId + "_rate").val(),
qty = $("#" + editingRowId + "_qty").val(),
newAmount = parseFloat(rate) * parseFloat(qty);
$("#" + editingRowId + "_amount").val(isFinite(newAmount) ? newAmount : 0);
},
myEditParam = {
keys: true,
oneditfunc: function (id) {
editingRowId = id;
},
afterrestorefunc: function (id) {
editingRowId = undefined;
},
aftersavefunc: function (id) {
var $this = $(this),
rate = $this.jqGrid("getCell", id, "rate"),
qty = $this.jqGrid("getCell", id, "qty"),
newAmount = parseFloat(rate) * parseFloat(qty);
$this.jqGrid("setCell", id, "amount", newAmount);
editingRowId = undefined;
}
},
numInput = {
type: 'keydown',
fn: function (e) {
var key = e.which;
// allow only '0' <= key <= '9' or key = '.', Enter, Tab, Esc
if ((key < 48 || key > 57) && key !== $.ui.keyCode.PERIOD &&
key !== $.ui.keyCode.TAB && key !== $.ui.keyCode.ENTER && key !== $.ui.keyCode.ESCAPE) {
return false;
}
}
},
recompute = {
type: 'focusout',
fn: function (e) {
recomputeAmount();
}
};
$("#purchasedetailsgrid").jqGrid({
colModel: [
...
{name:'qty', index:'qty',editable:true,width:85,search:false,editrules:{number:true,maxlength:5},
editoptions: {
dataInit: function (elem) { $(elem).focus(function () { this.select(); }) },
dataEvents: [ numInput, recompute ]
}
},
{name:'rate', index:'rate',width:100,editable:true,search:false,editrules:{number:true,maxlength:10},
editoptions: {
dataInit: function (elem) { $(elem).focus(function () { this.select(); }) },
dataEvents: [ numInput, recompute ]
}
},
{name:'amount', index:'amount',width:100,editable:true,search:false,editrules:{number:true,maxlength:10}}
],
loadComplete: function () {
var gridIdSelector = '#' + $.jgrid.jqID(this.id);
if (this.rows.length > 1) {
//$(this).jqGrid('editRow', this.rows[1].id, myEditParam);
$(this).jqGrid('setSelection', this.rows[1].id, true);
setTimeout(function() {
// we should simulate click of the button not after the grid is loaded, but
// after the toolbar with the cliked button will be created by inlineNav
$(gridIdSelector + "_iledit").click();
}, 100);
} else {
setTimeout(function() {
// we should simulate click of the button not after the grid is loaded, but
// after the toolbar with the cliked button will be created by inlineNav
$(gridIdSelector + "_iladd").click();
}, 100);
}
}
});
jQuery("#purchasedetailsgrid").jqGrid('navGrid','#purchasedetailstoolbar',
{view:false,edit:false,add:false,del:false,search: false, refreshtitle: "Reload Grid"});
jQuery("#purchasedetailsgrid").jqGrid('inlineNav','#purchasedetailstoolbar',
{edit: true, add: true, editParams: myEditParam, addParams: {addRowParams: myEditParam}});
If it's needed I can comment unclear parts of the code.

Categories

Resources