JQGrid date sorting and search - javascript

I am currently displaying a particular set of data in jqgrid. I want to sort and search the column Job Date, but it does not work.
The date is being displayed as 2015-08-26 but neither sorting nor search works.
Am I missing something.
var gridSelector = "#tblist";
var emptyMsgDiv = $("<div style=\"text-align:center\"><span style='color:red;font-size:24px'>No records found</span></div>");
jQuery(gridSelector).jqGrid({
url: '#Url.Action("ListActivities", "DailyActivity")',
loadonce: true,
datatype: 'json',
shrinkToFit: true,
autowidth: true,
mtype: 'GET',
ignoreCase: true,
colNames: ['Edit', 'ActivityID', 'Job No', 'Job Date',...],
colModel: [
{ name: 'Edit', index: 'Edit', formatter: EditBind, width: '50px', search: false, sortable: false },
{ name: 'ActivityID', index: 'ActivityID', hidden: true },
{ name: 'DOWJobNumber', index: 'DOWJobNumber', align: 'left', width: '100px' },
{
name: 'DOWJobDate', index: 'DOWJobDate', width: '70px',
formatter: 'date',
sorttype: 'date',
formatoptions: {srcformat:'ISO8601Long', newformat: 'ISO8601Short' },
datefmt: 'ISO8601Short',
searchoptions: {
sopt: ['eq', 'gt', 'ge'],
dataInit: function (el) {
$(el)
.datepicker({ dateFormat: "yy-mm-dd" })
.change(function () {
$(gridSelector)[0].triggerToolbar();
});
}
}
},
{ ... },...
],
height: 'auto',
pager: '#gridpager',
rowNum: 20,
rowList: [5, 10, 20, 50, 100],
sortname: 'ActivityID',
sortorder: 'desc',
jsonReader: {
repeatitems: false,
root: function (obj) { return obj; },
page: function (obj) { return 1; },
total: function (obj) { return 1; },
records: function (obj) { return obj.length; }
},
loadError: function (xhr, st, err) {
bootbox.alert("Error retrieving data!");
},
emptyrecords: 'No Records found',
loadComplete: function () {
emptyMsgDiv.insertAfter($('#tblist').parent());
var ts = this;
if (ts.p.reccount === 0) {
$(this).hide();
emptyMsgDiv.show();
} else {
$(this).show();
emptyMsgDiv.hide();
}
}
})
.jqGrid('filterToolbar', { stringResult: true, searchOnEnter: false, defaultSearch: "cn" });
Edit: It looks like the search is being made on the JSON format(/Date(1430937000000)/). How can this be changed to search and sort using the specified date format

I had to format the date time as text in the controller and processed it in the JQGrid as below
{
name: 'DOWJobDateText', index: 'DOWJobDateText', width: '80px',
formatter: 'date',
sorttype: 'date',
formatoptions: { srcformat: 'd/m/Y', newformat: 'd/m/Y' },
datefmt: 'd/m/Y',
searchoptions: {
dataInit: function (el) {
$(el)
.datepicker({ dateFormat: "dd/mm/yy" })
.change(function () {
$(gridSelector)[0].triggerToolbar();
});
}
}
}

Related

jqGrid inline-edit POST without editurl?

I am trying to find the information about editurl. Currently, i am working on the framework which does not permit editurl. The calls must go through javascript function which in-turn invokes the component on serverside.
Question is it possible to POST the data to javascript function instead of editurl?
I am experimenting with following:
$(document).ready(function () {
console.log(">>>1");
//--
action.setCallback(this, function(a) {
if (a.getState() === "SUCCESS") {
result = a.getReturnValue();
console.log(result);
//---=
var editActionOptions = {
keys: true,
url:null,
oneditfunc: function (rowid) {
console.log("row with rowid=" + rowid + " is editing.");
},
aftersavefunc: function (rowid, response, options) {
console.log("row with rowid=" + rowid + " is successfuly modified.");
}
};
//-------------------------------------------------------------------------------------------------------
$("#jqGrid").jqGrid({
editurl: 'clientArray',
datatype: "local",
data:result,
colModel: [
{
label: "Edit Actions",
name: "actions",
width: 100,
formatter: "actions",
formatoptions: {
keys: true,
editOptions: {},
addOptions: {},
delOptions: {}
}
},
{
labe: 'ID',
name: 'empid',
width: 75
},
{
label : 'Name',
name: 'Name',
width: 140,
editable: true // must set editable to true if you want to make the field editable
},
{
label: 'dob',
name: 'dob',
width: 100,
editable: true
},
{
label: 'dln',
name: 'dln',
width: 120,
editable: true
}
],
sortname: 'empid',
loadonce: true,
onSelectRow: editRow,
onSave:onSaveRow,
editParams: editActionOptions,
width: 780,
height: 400,
rowNum: 150,
pager: "#jqGridPager"
});
//------------------------------------------------------------------------------------------------------
} else if (a.getState() === "ERROR") {
$A.log("Errors", a.getError());
}
});
$A.enqueueAction(action);
var lastSelection;
function editRow(id) {
console.log(id);
if (id && id !== lastSelection) {
var grid = $("#jqGrid");
grid.jqGrid('restoreRow',lastSelection);
grid.jqGrid('editRow',id, {keys: true} );
lastSelection = id;
}
};
function onSaveRow(id){
console.log(id);
}

Unable to set date format & dropdown text in jqGrid

I am using jqGrid to display data. Data is in xml format.
I am unable to format date column (source format : yyyyMMdd, target format : dd-mm-yyy).
My Grid is unable to display text value from select, It shows values instead of text.
Strange thing is it is working in some other screen.
<SalesOpportunitiesLines>
<row>
<LineNum>0</LineNum>
<SalesPerson>1</SalesPerson>
<StartDate>20131126</StartDate>
<ClosingDate>20131126</ClosingDate>
<StageKey>1</StageKey>
<PercentageRate>0.000000</PercentageRate>
<MaxLocalTotal>1000000.000000</MaxLocalTotal>
<DocumentType>bodt_MinusOne</DocumentType>
<BPChanelName>ACCM Services</BPChanelName>
<BPChanelCode>CLINAC0709</BPChanelCode>
<SequenceNo>366</SequenceNo>
<DataOwnershipfield>1</DataOwnershipfield>
<BPChannelContact>1212</BPChannelContact>
</row>
</SalesOpportunities>
$("#uxStages").jqGrid({
datatype: 'xmlstring',
datastr: xmlstring,
mtype: 'GET',
ajaxGridOptions: { contentType: 'application/json; charset=utf-8' },
xmlReader: { repeatitems: false, root: "BO>SalesOpportunitiesLines", row: 'row' },
colNames: ['LineNum', 'Star tDate', 'Clos Date', 'Sales Employee', 'Stage', 'Percentage', 'Potential Amount', 'Document Type', 'Doc. No.', 'Owner'],
colModel: [
{ name: 'LineNum', key: true, index: 'LineNum', hidden: true, sortable: false, width: 60 },
{ name: 'StartDate', key: false, index: 'StartDate', sortable: false, align: "left", width: 90,
editable: true,
formatter: 'date',
formatoptions: { srcformat: 'yyyyMMdd', newformat: 'd-M-y' },
editoptions: {
dataInit: function (elem) {
$(elem).datepicker({ dateFormat: 'dd-M-yy' });
}
}
},
{ name: 'ClosingDate', key: false, index: 'ClosingDate', sortable: false, align: "left", width: 90,
editable: true,
formatter: 'date',
formatoptions: { srcformat: 'yyyyMMdd', newformat: 'd-M-y' },
editoptions: {
dataInit: function (elem) {
$(elem).datepicker({ dateFormat: 'dd-M-yy' });
}
}
},
{ name: 'SalesPerson', key: false, index: 'SalesPerson', sortable: false, width: 80,
editable: true,
edittype: "select"
},
{ name: 'StageKey', key: false, index: 'StageKey', hidden: false, sortable: false, width:80,
editable: true,
edittype: "select"
},
{ name: 'PercentageRate', key: false, index: 'PercentageRate', sortable: false, width: 60 },
{ name: 'MaxLocalTotal', key: false, index: 'MaxLocalTotal', sortable: false, width: 100,
editable: true,
edittype: "text",
formatter: 'currency',
formatoptions: { thousandsSeparator: ',' }
},
{ name: 'DocumentType', key: false, index: 'DocumentType', sortable: false, width: 90,
editable: true,
edittype: 'select',
formatter: 'select',
editoptions: { value: "bodt_MinusOne:;bodt_Quotation:Sales Quotations;bodt_Order:Sales Orders;bodt_DeliveryNote:Deliveries;bodt_Invoice:A/R Invoice" }
},
{ name: 'DocumentNumber', key: false, index: 'DocumentNumber', sortable: false, width: 40 },
{ name: 'DataOwnershipfield', key: false, index: 'DataOwnershipfield', hidden: false, sortable: false, width: 60,
editable: true,
edittype: "select"
}
],
rowNum: 100,
viewrecords: true,
gridview: true,
rownumbers: true,
height: 150,
loadonce: true,
width: 1120,
scrollOffset: 0,
ondblClickRow: function (rowid) {
var grid = $("#uxStages");
var selectedRowId = grid.jqGrid('getGridParam', 'selrow');
lastSelection = selectedRowId;
grid.jqGrid('editRow', selectedRowId, true, null, null, null, null, OnSuccessEdit_Stages);
$('#' + selectedRowId + "_StageKey").css('width', '100%');
$('#' + selectedRowId + "_SalesPerson").css('width', '100%');
$('#' + selectedRowId + "_DataOwnershipfield").css('width', '100%');
},
loadComplete: function () {
var ids = $("#uxStages").jqGrid('getDataIDs');
for (var i = 0; i < ids.length; i++) {
var id = ids[i];
if (i < ids.length - 1) {
$('#' + $.jgrid.jqID(id)).addClass('not-editable-row');
$('#' + $.jgrid.jqID(id)).addClass('ui-state-error');
}
}
},
onSelectRow: function (id) {
if (id && id !== lastSelection) {
var grid = $("#uxStages");
$('#uxStages').saveRow(lastSelection);
}
}
}).jqGrid('navGrid', { edit: true, edit: true, add: true, del: true, searchOnEnter: false, search: false }, {}, {}, {}, { multipleSearch: false }).trigger('reloadGrid');
$("#uxStages").setColProp('SalesPerson', { edittype: "select", editoptions: { value: GetSalesValues()} }); //Here i m fetching values in namedvalue pairs
$("#uxStages").setColProp('StageKey', { edittype: "select", editoptions: { value: GetStagesValues()} }); //Here i m fetching values in namedvalue pairs
$("#uxStages").setColProp('DataOwnershipfield', { edittype: "select", editoptions: { value: GetDataOwnershipValues()} }); //Here i m fetching values in namedvalue pairs
Can anybody help me out?
The predefined formatter: "date" of jqGrid don't support input fields without separators. So you have to use custom formatter. The implementation could be something like the following
formatter: function (cellValue, opts, rawdata, action) {
if (action === "edit") {
// input data have format "dd-mm-yy" format - "20-03-2015"
var input = cellValue.split("-");
if (input.length === 3) {
return input[0] + "-" + input[1] + "-" + input[2];
}
} else if (cellValue.length === 8) {
// input data have format "yymmdd" format - "20150320"
var year = cellValue.substr(0,4), month = cellValue.substr(4,2),
day = cellValue.substr(6,2);
return day + "-" + month + "-" + year;
}
return cellValue; // for empty input for example
}
Depend on other options (like the usage of loadonce: true) and depend on exact version of jqGrid which you use, you could need to implement additional callbacks in the column. For example if you use loadonce: true then the editing data will be saved locally. To hold the data in the same format as input data one can use saveLocally callback of free jqGrid (see here). In the case you can implement saveLocally callback in the column as the following
saveLocally: function (options) {
var input = String(options.newValue).split("-");
options.newItem[options.cmName] = input.length === 3 ?
input[2] + input[1] + input[0] :
options.newValue;
}
See the corresponding demo uses the above code. It uses local input data in the same format. The date will be displayed in the desired format, but the edited data will be saved locally in the same format like original date.

Issues Loading jqGrid with 25,000 Rows

I'm having some difficulty loading my jqGrid with a big amount of rows. Once my document is ready I'm calling a Javascript function that gets a collection of objects from an API and then adds the row data to the grid. Everything has been working fine, but now I have over 20,000 rows, so the grid never loads. Is there something I can do to fix this? Is it possible to only paint the data that the user can see? For example, if the row number on the pager is set to 50, can I simply only load 50 rows and not all 25,000?
Here's my grid:
$(function () {
$("#grid").jqGrid({
datatype: "local",
loadonce: false,
height: "auto",
search: true,
title: false ,
autowidth: true,
shrinkToFit: true,
searchOnEnter: true,
colNames: ['ID', 'BDO Number', 'BDO Date', 'Delivery Date', 'Miles', 'Zip Code', 'Zone', 'Fuel Surcharge', 'Driver', 'Driver Rate', 'Total Driver Pay', 'Order', 'Driver ID',
'Vendor ID', 'Vendor', 'Airport', 'Airline', 'Claim Reference', 'Clear Date', 'Mileage', 'Mileage Cost', 'Special', 'Special Cost', 'Exc Cost', 'Pickup Date', 'Total Delivery Cost',
'Vendor Profit', 'Driver Percent', 'Driver Fuel Surcharge', 'Total Driver Reported', 'Payment', 'User Cleared', 'Excess Costs', 'Additional Fees', 'DriverCostSchemaID'],
colModel: [
{ name: 'ID', index: 'ID', hidden: true },
{ name: 'BDONumber', index: 'BDONumber', align: 'center', classes: 'gridButton' },
{ name: 'BDODate', index: 'BDODate', width: 250, align: 'center', formatter: 'date', formatoptions: { newformat: 'l, F d, Y g:i:s A' } },
{ name: 'DeliveryDate', index: 'DeliveryDate', width: 250, align: 'center', formatter: 'date', formatoptions: { newformat: 'l, F d, Y g:i:s A' } },
{ name: 'Miles', index: 'Miles', width: 40, align: 'center' },
{ name: 'ZipCode', index: 'ZipCode', width: 55, align: 'center' },
{ name: 'Zone', index: 'Zone', width: 40, align: 'center' },
{ name: 'FuelFloat', index: 'FuelFloat', width: 50, align: 'center', formatter: money, sorttype: 'float' },
{ name: 'DriverName', index: 'DriverName', width: 125, align: 'center' },
{ name: 'RateFloat', index: 'RateFloat', width: 75, align: 'center', formatter: money, sorttype: 'float' },
{ name: 'PayFloat', index: 'PayFloat', width: 75, align: 'center', formatter: money, sorttype: 'float' },
{ name: 'Order', index: 'Order', hidden: true },
{ name: 'Driver', index: 'Driver', hidden: true },
{ name: 'Vendor', index: 'Vendor', hidden: true },
{ name: 'Airport', index: 'Airport', hidden: true },
{ name: 'Airline', index: 'Airline', hidden: true },
{ name: 'VendorName', index: 'VendorName', hidden: true },
{ name: 'ClaimReference', index: 'ClaimReference', hidden: true },
{ name: 'ClearDate', index: 'ClearDate', hidden: true, formatter: 'date', formatoptions: { newformat: 'l, F d, Y g:i:s A' } },
{ name: 'Mileage', index: 'Mileage', hidden: true },
{ name: 'MileageCost', index: 'MileageCost', hidden: true, formatter: money },
{ name: 'Special', index: 'Special', hidden: true },
{ name: 'SpecialCost', index: 'SpecialCost', hidden: true, formatter: money },
{ name: 'ExcCost', index: 'ExcCost', hidden: true, formatter: money },
{ name: 'PickupDate', index: 'PickupDate', hidden: true, formatter: 'date', formatoptions: { newformat: 'l, F d, Y g:i:s A' } },
{ name: 'TotalDeliveryCost', index: 'TotalDeliveryCost', hidden: true, formatter: money },
{ name: 'VendorProfit', index: 'VendorProfit', hidden: true, formatter: money },
{ name: 'DriverPercent', index: 'DriverPercent', hidden: true },
{ name: 'DriverFuelSurcharge', index: 'DriverFuelSurcharge', hidden: true, formatter: money },
{ name: 'TotalDriverReported', index: 'TotalDriverReported', hidden: true, formatter: money },
{ name: 'Payment', index: 'Payment', hidden: true },
{ name: 'UserCleared', index: 'UserCleared', hidden: true },
{ name: 'ExcCost', index: 'ExcCost', hidden: true },
{ name: 'AdditionalFees', index: 'AdditionalFees', hidden: true, formatter: money },
{ name: 'DriverCostSchemaID', index: 'DriverCostSchemaID', hidden: true },
],
rowNum: 100,
rowList: [100, 500, 1000, 100000],
viewrecords: true,
pager: "pager",
sortorder: "desc",
sortname: "DeliveryDate",
ignoreCase: true,
headertitles: true,
emptyrecords: "There are no results.",
})
$("#grid").jqGrid('filterToolbar', { stringResult: true, searchOnEnter: true, defaultSearch: 'cn' });
GetBDOs();
});
And the GetBDOs function:
function GetBDOs() {
var request = $.ajax({
url: "#Url.Action("GetBDOs", "DPAdmin")",
type: "GET",
cache: false,
async: true,
dataType: "json"
});
request.done(function (results) {
var thegrid = $("#grid");
thegrid.clearGridData();
for (var i = 0; i < 100; i++) {
thegrid.addRowData(i + 1, results[i]);
}
thegrid.trigger("reloadGrid");
});
}
Which calls this:
[Authorize]
public JsonResult GetBDOs()
{
List<BDO> BDOs= new List<BDO>();
// Get all BDOs
BDOs = WebInterface.GetBDOs();
var jsonResult = Json(BDOs.ToArray(), JsonRequestBehavior.AllowGet);
jsonResult.MaxJsonLength = int.MaxValue;
return jsonResult;
}
WebInterface.GetBDOs simply hits the database and grabs all the current BDO objects, which is now between 20,000 - 25,000 and freezes the grid. Any help with this?
You really should be paginating that data on the server side before sending it back to the browser. Then all you need to do is fetch the next/prev page and redraw the grid.
The part
var thegrid = $("#grid");
thegrid.clearGridData();
for (var i = 0; i < 100; i++) {
thegrid.addRowData(i + 1, results[i]);
}
thegrid.trigger("reloadGrid");
of GetBDOs function makes performance problems definitively. Instead of calling addRowData in the loop you should set data parameter to results with respect of setGridParam:
var thegrid = $("#grid");
thegrid.clearGridData();
thegrid.jqGrid("setGridParam", {data: results});
thegrid.trigger("reloadGrid");
Additionally it's very important to add gridview: true option to jqGrid.
Even better seems to me to replace use url: "#Url.Action("GetBDOs", "DPAdmin")" as jqGrid parameters together with datatype: "json" and loadonce: true. It will makes the same Ajax call to the server and fill the grid with all 20000 or 25000 rows of data, but placing only 100 first rows in the grid.
One more recommendation will be to use key: true property in ID column. It will inform jqGrid to use the value from ID column as rowid (the value of id attributes of <tr> elements of the grid). You should consider additionally to remove a lot of hidden columns and saves the data only in the internal data option of the grid.

Capture change/click event of drop down in jqGrid

The click event on my drop down does not fire. I do not see an alert and when I add a breakpoint in Firebug, it does not reach the breakpoint. It does reach the click and double click events if I breakpoint those.
Specifically, when I:
Double click to edit a line
Pick the Customer Drop Down and pick something else
Move to another line
then the line
alert("I changed");
Does not run.
I wonder if it's because when I move to another line, the value gets reverted (even though I have commented out the restoreRow method)
Am I using the right event to capture when my drop down value changes (without having to change focus).
$(document).ready(
function () {
// This is executed as soon as the DOM is loaded and before the page contents are loaded
var lastsel;
// $ is short for JQuery which is in turn a super overloaded function that does lots of things.
// # means select an element by its ID name, i.e. below we have <table id="ts"
$("#ts").jqGrid({
//=============
// Grid Setup
url: 'Timesheet/GridData/',
datatype: 'json',
mtype: 'GET',
pager: $('#pager'),
rowNum: 30,
rowList: [10, 20, 30, 40, 80],
viewrecords: true,
imgpath: '/Content/themes/base/images',
caption: 'Timesheet',
height: 450,
// Column definition
colNames: ['hCustomer_ID', 'hProject_ID', 'hTask_ID', 'Date', 'Customer', 'Project', 'Task', 'Description', 'Hours', '$'],
colModel: [
{ name: 'hCustomer_ID', index: 'hCustomer_ID', editable: false, hidden: true },
{ name: 'hProject_ID', index: 'hProject_ID', editable: false, hidden: true },
{ name: 'hTask_ID', index: 'hTask_ID', editable: false, hidden: true },
{ name: 'tsdate', index: 'tsdate', width: 80, editable: true, datefmt: 'yyyy-mm-dd' },
{ name: 'Customer', index: 'Customer', width: 250, align: 'left', editable: true, edittype: "select",
editoptions: { dataUrl: 'Timesheet/CustomerList' },
dataEvents: [
{
type: 'click',
fn: function (e) {
alert("I changed");
}
}]
},
{ name: 'Project', index: 'Project', width: 250, align: 'left', editable: true, edittype: "select", editoptions: { dataUrl: 'Timesheet/ProjectList'} },
{ name: 'Task', index: 'Task', width: 250, align: 'left', editable: true, edittype: "select", editoptions: { dataUrl: 'Timesheet/TaskList'} },
{ name: 'Desc', index: 'Desc', width: 300, align: 'left', editable: true },
{ name: 'Hours', index: 'Hours', width: 50, align: 'left', editable: true },
{ name: 'Charge', index: 'Charge', edittype: 'checkbox', width: 18, align: 'center', editoptions: { value: "0:1" }, formatter: "checkbox", formatoptions: { disabled: false }, editable: true }
],
//=============
// Grid Events
// when selecting, undo anything else
onSelectRow: function (rowid, iRow, iCol, e) {
if (rowid && rowid !== lastsel) {
// $(this).jqGrid('restoreRow', lastsel);
lastsel = rowid;
}
},
// double click to edit
ondblClickRow: function (rowid, iRow, iCol, e) {
// browser independent stuff
if (!e) e = window.event;
var element = e.target || e.srcElement
// When editing, change the drop down datasources to filter on the current parent
$(this).jqGrid('setColProp', 'Project', { editoptions: { dataUrl: 'Timesheet/ProjectList?Customer_ID=' + $(this).jqGrid('getCell', rowid, 'hCustomer_ID')} });
$(this).jqGrid('setColProp', 'Task', { editoptions: { dataUrl: 'Timesheet/TaskList?CustomerProject_ID=' + $(this).jqGrid('getCell', rowid, 'hProject_ID')} });
// Go into edit mode (automatically moves focus to first field)
// Use setTimout to apply the focus and datepicker after the first field gets the focus
$(this).jqGrid(
'editRow',
rowid,
{
keys: true,
oneditfunc: function (rowId) {
setTimeout(function () {
$("input, select", element).focus();
$("#" + rowId + "_tsdate").datepicker({ dateFormat: 'yy-mm-dd' });
}, 50);
}
}
);
}, // end ondblClickRow event handler
postData:
{
startDate: function () { return $('#startDate').val(); }
}
}); // END jQuery("#ts").jqGrid
$("#ts").jqGrid('navGrid', '#pager', { view: false, edit: false, add: false, del: false, search: false });
$("#ts").jqGrid('inlineNav', "#pager");
}); // END jQuery(document).ready(function () {
REVISED WORKING CODE:
$(document).ready(
function () {
// This is executed as soon as the DOM is loaded and before the page contents are loaded
var lastsel;
// $ is short for JQuery which is in turn a super overloaded function that does lots of things.
// # means select an element by its ID name, i.e. below we have <table id="ts"
$("#ts").jqGrid({
//=============
// Grid Setup
url: 'Timesheet/GridData/',
datatype: 'json',
mtype: 'GET',
pager: $('#pager'),
rowNum: 30,
rowList: [10, 20, 30, 40, 80],
viewrecords: true,
caption: 'Timesheet',
height: 450,
// Column definition
colNames: ['hCustomer_ID', 'hProject_ID', 'hTask_ID', 'Date', 'Customer', 'Project', 'Task', 'Description', 'Hours', '$'],
colModel: [
{ name: 'hCustomer_ID', index: 'hCustomer_ID', editable: false, hidden: true },
{ name: 'hProject_ID', index: 'hProject_ID', editable: false, hidden: true },
{ name: 'hTask_ID', index: 'hTask_ID', editable: false, hidden: true },
{ name: 'tsdate', index: 'tsdate', width: 80, editable: true, datefmt: 'yyyy-mm-dd' },
{ name: 'Customer', index: 'Customer', width: 250, align: 'left', editable: true, edittype: "select",
editoptions: {
dataUrl: 'Timesheet/CustomerList',
dataEvents: [
{
type: 'change',
fn: function (e) {
alert("I changed");
}
}]
}
},
{ name: 'Project', index: 'Project', width: 250, align: 'left', editable: true, edittype: "select", editoptions: { dataUrl: 'Timesheet/ProjectList'} },
{ name: 'Task', index: 'Task', width: 250, align: 'left', editable: true, edittype: "select", editoptions: { dataUrl: 'Timesheet/TaskList'} },
{ name: 'Desc', index: 'Desc', width: 300, align: 'left', editable: true },
{ name: 'Hours', index: 'Hours', width: 50, align: 'left', editable: true },
{ name: 'Charge', index: 'Charge', edittype: 'checkbox', width: 18, align: 'center', editoptions: { value: "0:1" }, formatter: "checkbox", formatoptions: { disabled: false }, editable: true }
],
//=============
// Grid Events
// when selecting, undo anything else
onSelectRow: function (rowid, iRow, iCol, e) {
if (rowid && rowid !== lastsel) {
// $(this).jqGrid('restoreRow', lastsel);
lastsel = rowid;
}
},
// double click to edit
ondblClickRow: function (rowid, iRow, iCol, e) {
// browser independent stuff
if (!e) e = window.event;
var element = e.target || e.srcElement
// When editing, change the drop down datasources to filter on the current parent
$(this).jqGrid('setColProp', 'Project', { editoptions: { dataUrl: 'Timesheet/ProjectList?Customer_ID=' + $(this).jqGrid('getCell', rowid, 'hCustomer_ID')} });
$(this).jqGrid('setColProp', 'Task', { editoptions: { dataUrl: 'Timesheet/TaskList?CustomerProject_ID=' + $(this).jqGrid('getCell', rowid, 'hProject_ID')} });
// Go into edit mode (automatically moves focus to first field)
// Use setTimout to apply the focus and datepicker after the first field gets the focus
$(this).jqGrid(
'editRow',
rowid,
{
keys: true,
oneditfunc: function (rowId) {
setTimeout(function () {
$("input, select", element).focus();
$("#" + rowId + "_tsdate").datepicker({ dateFormat: 'yy-mm-dd' });
}, 50);
}
}
);
}, // end ondblClickRow event handler
postData:
{
startDate: function () { return $('#startDate').val(); }
}
}); // END jQuery("#ts").jqGrid
$("#ts").jqGrid('navGrid', '#pager', { view: false, edit: false, add: false, del: false, search: false });
$("#ts").jqGrid('inlineNav', "#pager");
}); // END jQuery(document).ready(function () {
Additionally it's unclear why you use both inlineNav and manual call of editRow inside of ondblClickRow? If you would select row and then click on the button from the navigator the dataUrl will not be adjusted.
The reason of the main problem which you describe is wrong usage of dataEvents. In the documentation of editoptions you will find the dataEvents is the property of editoptions like dataUrl for example. Currently you placed dataEvents on the wrong place in colModel.
I would recommend you additionally to read the answer which describe how you can use dataUrl which parameters depend on the current selected row. Additionally I would recommend you to verify that you set Cache-Control in the response of dataUrl (see the answer). Alternatively you can use anothe option described here.

jqgrid getChangedCells not returning changed cells

I am trying to edit and save multiple rows from jqgrid. The getChangedCells is not returning any values.
The code is as below:
<style>
.hlabel{font-weight:bold;font-size:10pt;}
.hdata{font-size:10pt;}
</style>
<script>
//this is a formatter for showing images
function imageFormatter(cellvalue, options, rowObject) {
return "<img src='" + cellvalue + "'/>";
};
//this gets called on edit mode to display datepickers.
function onGridEdit(myRowID) {
$("#" + myRowID + "_booked").datepicker({ dateFormat: 'dd/mm/yy' });
$("#" + myRowID + "_vesselarrival").datepicker({ dateFormat: 'dd/mm/yy' });
$("#" + myRowID + "_vesseldock").datepicker({ dateFormat: 'dd/mm/yy' });
$("#" + myRowID + "_markdown").datepicker({ dateFormat: 'dd/mm/yy' });
// this will set focus on the Invested column so the datepicker doesn't fire
$("#" + myRowID + "_vesselname").get(0).focus();
}
$(function () {
var lastsel2
//creating the grid
$("#gditems").jqGrid({
url: 'handlers/items.ashx?id=' + PID,
datatype: "xml",
mtype: "POST",
colNames: ['Style', 'Altcode2', 'Colour', 'Group', '800', '999', 'Order', 'Received', 'Due', 'B/O', 'Image', 'Out/Full', 'Booked', 'Current', 'Slip', 'Arrival', 'Dock', 'Name', 'Freight', 'RRP', 'Mark Down', 'Sell', 'Cost'],
colModel: [
{ name: 'code1', index: 'code1', width: '50', sortable: true },
{ name: 'code2', index: 'code2', width: '30', sortable: true },
{ name: 'Due', index: 'Due', sorttype: 'integer', width: '20', sortable: false },
{ name: 'image', index: 'image', width: '30', formatter: imageFormatter, sortable: false },
{ name: 'booked', index: 'booked', width: '30', sortable: false, datefmt: "d/m/Y", editable: true, editrules: { date: true} },
{ name: 'date1', index: 'date1', width: '40' },
{ name: 'slip', index: 'slip', width: '30', sortable: false },
{ name: 'arrival', index: 'arrival', width: '30', sortable: false, datefmt: "d/m/Y", editable: true, editrules: { date: true} },
{ name: 'dock', index: 'dock', width: '30', sortable: false, datefmt: "d/m/Y", editable: true, editrules: { date: true} },
{ name: 'vname', index: 'vname', width: '30', sortable: false, editable: true },
{ name: 'price', index: 'price', sorttype: 'currency', width: '30', formatter: 'currency', formatoptions: { decimalPlaces: 2, prefix: "£"} },
{ name: 'date2', index: 'date2', width: '30', sortable: false, editable: true, datefmt: "d/m/Y", editrules: { date: true} },
{ name: 'price2', index: 'price2', sorttype: 'currency', width: '30', formatter: 'currency', formatoptions: { decimalPlaces: 2, prefix: "£"}}],
//saving into clientarray
onSelectRow: function (id) {
if (id && id !== lastsel2) {
jQuery("#gdpoitems").saveRow(lastsel2, false, 'clientArray');
jQuery('#gdpoitems').editRow(id, true, onGridEdit, null, 'clientArray');
lastsel2 = id;
}
},
editurl: "clientArray",
cellSubmit: 'clientArray',
rowNum: 20,
height: "100%",
autowidth: true,
rowList: [20, 30],
pager: jQuery('#pgitems'),
viewrecords: true,
sortorder: "asc",
caption: "",
loadonce: false
});
//adding buttons to the nav bar
jQuery("#gditems")
.navGrid('#pgitems', { edit: false, add: false, del: false, search: false }).navButtonAdd('#pgitems', {
caption: "Save",
buttonicon: "ui-icon-disk",
onClickButton: function () {
$.post("handlers/details.ashx?id=" + PID, { c1: $("#txtc1").val(), c2: $("#txtc2").val(), c3: $("#txtc3").val() }, function (data) {
//trying to get the edited data.
var ret = $("#gditems").getChangedCells('all');
var ret2 = JSON.stringify(ret);
alert(ret);
$.ajax({
type: "POST",
url: "handlers/items.ashx?edit=1&id=" + PID,
data: ret2,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response, textStatus, xhr) {
alert("success");
},
error: function (xhr, textStatus, errorThrown) {
alert("error");
}
});
});
},
position: "last"
})
.navButtonAdd('#pgitems', {
caption: "Cancel",
buttonicon: "ui-icon-cancel",
onClickButton: function () {
$("#header").show();
$("#detail").hide();
return false;
},
position: "last"
});
</script>
<div>
<br />
<table id="gditems">
</table>
<div id="pgitems"> </div>
</div>

Categories

Resources