Capture change/click event of drop down in jqGrid - javascript

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.

Related

JQGrid date sorting and search

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();
});
}
}
}

jqGrid dynamically change search operator type on button click

This is my jqgrid
Grid related code
var lastsel2;
var containsOrNot = 'contains';
jQuery(document).ready(function(){
jQuery("#list").jqGrid({
url: "{{ asset('/app_dev.php/_thrace-datagrid/data/item_lookup_management') }}",
postData: {
masterGridRowId: {{ VPK }}
},
datatype: "json",
mtype: 'POST',
colNames: ['Item No', 'Description 1', 'Vendor Item No','Report Dec','Location','On Hand','Exp balance','Available now','Lead Time','Type', 'Vendor #', 'Status', 'Stocked', 'Product Line', 'Creator'],
colModel: [
{
name: "I_ItemNumID",
index: "u.I_ItemNumID",
editable: false,
align: 'left',
searchoptions:{sopt:['cn','eq','ne','lt','le','gt','ge','bw','ew','nc']},
width: '70'
},
{
name: "I_Desc1",
index: "u.I_Desc1",
editable: false,
align: 'left',
searchoptions:{sopt:['cn','eq','ne','lt','le','gt','ge','bw','ew','nc']},
width: '70'
},
{
name: "I_VendorItemNum",
index: "u.I_VendorItemNum",
editable: false,
align: 'left',
searchoptions:{sopt:['cn','eq','ne','lt','le','gt','ge','bw','ew','nc']},
width: '100'
},
{
name: "I_ReportDec",
index: "u.I_ReportDec",
editable: false,
align: 'left',
searchoptions:{sopt:['cn','eq','ne','lt','le','gt','ge','bw','ew','nc']},
width: '100'
},
{
name: "I_BinNum",
index: "u.I_BinNum",
editable: false,
align: 'left',
searchoptions:{sopt:['cn','eq','ne','lt','le','gt','ge','bw','ew','nc']},
width: '100'
},
{
name: "I_OnHandTotal",
index: "u.I_OnHandTotal",
editable: false,
align: 'left',
searchoptions:{sopt:['cn','eq','ne','lt','le','gt','ge','bw','ew','nc']},
width: '100'
},
{
name: "R_ClosingBalance",
index: "u.R_ClosingBalance",
editable: false,
align: 'left',
searchoptions:{sopt:['cn','eq','ne','lt','le','gt','ge','bw','ew','nc']},
width: '100'
},
{
name: "R_BalanceActual",
index: "u.R_BalanceActual",
editable: false,
align: 'left',
searchoptions:{sopt:['cn','eq','ne','lt','le','gt','ge','bw','ew','nc']},
width: '100'
},
{
name: "I_LeadTime",
index: "u.I_LeadTime",
editable: false,
align: 'left',
searchoptions:{sopt:['cn','eq','ne','lt','le','gt','ge','bw','ew','nc']},
width: '100'
},
{
name: "I_ItemType",
index: "u.I_ItemType",
editable: false,
align: 'left',
searchoptions:{sopt:['cn','eq','ne','lt','le','gt','ge','bw','ew','nc']},
width: '100'
},
{
name: "I_VendorNumID",
index: "u.I_VendorNumID",
editable: false,
align: 'left',
searchoptions:{sopt:['cn','eq','ne','lt','le','gt','ge','bw','ew','nc']},
width: '100'
},
{
name: "I_Status",
index: "u.I_Status",
editable: false,
width: 100,
searchoptions:{sopt:['cn','eq','ne','lt','le','gt','ge','bw','ew','nc']},
align: 'left'
},
{
name: "I_isStocked",
index: "u.I_isStocked",
editable: false,
width: 100,
searchoptions:{sopt:['cn','eq','ne','lt','le','gt','ge','bw','ew','nc']},
align: 'left'
},
{
name: "I_ProductLine",
index: "u.I_ProductLine",
editable: false,
width: 150,
searchoptions:{sopt:['cn','eq','ne','lt','le','gt','ge','bw','ew','nc']},
align: 'left'
},
{
name: "I_CreatedSysUser",
index: "u.I_CreatedSysUser",
editable: false,
width: 100,
searchoptions:{sopt:['cn','eq','ne','lt','le','gt','ge','bw','ew','nc']},
align: 'left'
}
],
ondblClickRow: function(rowid) {
var rowData = jQuery('#list').jqGrid ('getRowData', rowid);
window.opener.document.getElementById('productDetail_V_PK').value = rowid;
window.opener.document.getElementById('productDetail_V_Desc').value = rowData.I_ItemNumID;
window.close();
},
height: 400,
rowNum: 50,
rowTotal: 1000000,
width: 3000,
gridview: true,
autoencode: false,
pager: '#pager',
shrinkToFit: true,
sortable: true,
sortname:"u.id",
sortorder: "desc",
viewrecords: true,
//multiselect: true,
loadonce:false,
onCellSelect: function(row, col, content, event) {
var cm = jQuery("#list").jqGrid("getGridParam", "colModel");
//alert(cm[col].name);
if (window.getSelection) {
selection = window.getSelection();
} else if (document.selection) {
selection = document.selection.createRange();
}
selectionColumn = cm[col].name;
selection.toString() !== '' && $("#gs_"+selectionColumn).val(selection.toString());
},
rowList: [50, 100, 500, 1000]
});
jQuery("#list").jqGrid('navGrid',"#pager",{ del:false, add:false, edit:false},{multipleSearch:true}).navButtonAdd('#pager',{
caption: "Select",
buttonicon:"ui-icon-disk",
onClickButton: function(){
var myGrid = $('#list');
selectedRowId = myGrid.jqGrid ('getGridParam', 'selrow');
var rowData = jQuery('#list').jqGrid ('getRowData', selectedRowId);
if(selectedRowId != null)
{
window.opener.document.getElementById('productDetail_V_PK').value = selectedRowId;
window.opener.document.getElementById('productDetail_V_Desc').value = rowData.I_ItemNumID;
window.close();
}
else
{
$(function() {
$( "#dialog-message" ).dialog({
modal: true,
buttons: {
Ok: function() {
$( this ).dialog( "close" );
}
}
});
});
}
},
position:"last"
});
jQuery("#list").jqGrid('filterToolbar',{
searchOperators: true,
stringResult: true,
searchOnEnter : true,
sopt: ['cn','eq','ne','lt','le','gt','ge','bw','ew','nc'],
beforeSearch: function(){
if(containsOrNot == "notContains" && containsOrNot != "contains")
{
//CODE FOR EXCLUDE EXECUTE HERE
var i, l, rules, rule, $grid = $('#list'),
postData = $grid.jqGrid('getGridParam', 'postData'),
filters = $.parseJSON(postData.filters);
if (filters && typeof filters.rules !== 'undefined' && filters.rules.length > 0) {
rules = filters.rules;
for (i = 0; i < rules.length; i++) {
rule = rules[i];
console.log(rule.op);
if (rule.op === 'cn') {
// change contains to does not contain
rule.op = 'nc';
}
}
postData.filters = JSON.stringify(filters);
}
}
}}).navButtonAdd('#pager',{
caption: "Contains",
buttonicon:"ui-icon-disk",
onClickButton: function(){
containsOrNot = 'contains';
$("#list")[0].triggerToolbar();
},
position:"last"
}).navButtonAdd('#pager',{
caption: "Excludes",
buttonicon:"ui-icon-disk",
onClickButton: function(){
containsOrNot = 'notContains';
$("#list")[0].triggerToolbar();
},
position:"last"
});
jQuery('#list').jqGrid('gridResize');
});
My grid already has code for triggering the toolbar search.
$("#list")[0].triggerToolbar(); is doing my toolbarsearch on the click of a button defined in the footer part.
Currently the search is defaulted to contains. so when I select text from any column the filter of that column is populated with that selected text. And when I press on the Contains button the triggerToolbar is triggered properly.
What I would like to do? when I click on the Excludes button it should fire another triggerToolbar but with a does not contain filter. How can I dynamically change the default filter on the particular column?
Edit jqGrid version 4.8.2
UPDATE With Oleg's another answer here and the current answer I was able to achieve this. The code is updated and works as required.
What you want is not easy. You will have to change the operations in operation menu in every searching field. Moreover you will have to add first of all have to add searchoptions: { sopt: ['cn', 'nc']} options in all columns, because currently there are many fields which have no searchoptions.sopt. It means that one can search only by 'cn'.
Because of complexity of the way I would recommend you to choose an alternative way. I'd suggest you to add beforeSearch callback in filterToolbar. The callback onClickButton for "Excludes" and "Contains" buttons should set some variable to different value. The variable should be available inside of beforeSearch callback of filterToolbar. Inside of beforeSearch callback you can implement the following logic. If "Contains" button is clicked it should return false (continue searching). In case of "Excludes" button is clicked one should convert the string postData.filters to object and go through every element of rules and replace "cn" value of the op property to "nc". Finally one should convert the modified searching rule from object to string and return false too to continue searching. It should work.

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.

JQGrid: Dropdown, select the value, through addrow

In JQGrid I have used the dropdown column with the following code (in colModel):
{
name: 'CountryList', index: 'CountryList', width: 120, resizable: true,
sortable: false, editable: true, edittype: 'select', formatter: 'select',
formatoptions: {
disabled: false
},
editoptions: {
size : 1,
dataUrl : 'GetLists.ashx?Type=CountrLists&RegionID=2'),
dataEvents: [{
type: 'change',
fn: function (e) {
//$('input#Job_Number').val(this.value);
//alert(this.value);
}
}],
style: "width: 95%"
}
},
Problem:
When adding row (addrow), i want the added row to have the above mentioned dropdown column value selected, by passing a paramter (preferably value of select/option HTML control)
parameters =
{
rowID : undefined,
initdata: {
chkSave: "false", 'Label': 'test', people: 'Test person',
CountryList: '2', Notes: 'Test notes.'
},
position: "first",
useDefValues: true,
useFormatter: false,
addRowParams: { extraparam: {} }
};
$("#tbJQGrid").jqGrid('addRow', parameters);
Please provide some solution or alternatives.
To resolve this,used the "setColProp" property to modify the dataUrl:
$("#tbJQGrid").setColProp('CountryList', { editoptions: { dataUrl: 'GetLists.ashx?Type=CountrLists&RegionID=15' } });
Hope this helps.
Kindly add to the comments, in case better solution exist.

Categories

Resources