How to set a text to Jqgrid dropdown? - javascript

I want to set a default value to jqgrid dropdown when click the add new button. My Jqgrid code is following.
jQuery("#grdDrawdownSchedule").jqGrid({
url: RootUrl + 'ECB/DDSGridData',
datatype: 'json',
mtype: 'POST',
height: 130,
colNames: ['id', 'Drawdown Date', 'Currency', 'Amount'],
colModel: [
{ name: 'id', index: 'id', width: 30, sorttype: "int", editable: false, hidden: true },
{ name: 'DdDate', index: 'DdDate', width: 130, align: 'left', editable: true,
editoptions: {
readonly: 'readonly',
size: 10, maxlengh: 10,
dataInit: function (element) {
$(element).datepicker({ dateFormat: 'dd-M-yy', changeMonth: true,
changeYear: true, constrainInput: false, showOn: 'both',
buttonImage: RootUrl + 'Content/Images/grid_Calendar.png',
buttonText: 'Show Calendar',
buttonImageOnly: true
});
}
}
},
{ name: 'CurrencyName', index: 'CurrencyName', width: 120, editable: true, edittype: "select" },
{ name: 'Amount', index: 'Amount', align: "right", width: 120, editable: true,
editoptions: { size: "20", maxlength: "16", dataInit: function (element) {
$(element).keypress(function (e) {
$('#AvgMaturityLoan').val("0");
if (e.which != 8 && e.which != 0 && e.which != 46 && (e.which < 48 || e.which > 57)) {
return false;
}
var charCode = (e.which) ? e.which : e.keyCode;
if (charCode == 46 && this.value.split('.').length > 1)
return false;
});
}
}
},
//{ name: 'tadte', index: 'tdate', width: 130, "editable": true, "sorttype": "date", editrules: { "date": true }, "editoptions": { "dataInit": "initDateEdit"} },
],
loadComplete: function () {
$("#grdDrawdownSchedule").setColProp('CurrencyName', { editoptions: { value: JSON.parse(Currencies)} });
},
cellEdit: true,
rowNum: 100,
rownumbers: true,
cellsubmit: 'clientArray',
caption: "Drawdown Schedule",
multiselect: true,
shrinkToFit: false, forceFit: true,
width: 490,
postData: {
"lrnid": "0",
"data": ""
}
});
And my Add New button for the grid
$("#btnAddNewDrawdownSche").click(function () {
if (ValidateRow($("#grdDrawdownSchedule"))) {
var idAddRow = $("#grdDrawdownSchedule").getGridParam("reccount")
emptyItem = [{ id: idAddRow + 1, DrawdownDate: "", Currency: "", amount: ""}];
jQuery("#grdDrawdownSchedule").jqGrid('addRowData', 0, emptyItem);
$("#grdDrawdownSchedule").jqGrid('setCell', rowId, 'CurrencyName', selectedLoanCurrencyValue);
}
});
When I click the Add New button, Then initially I want to set the 'INR' value to the CurrencyName dropdown column. So how to set the default value to the Jqgrid's column.

Related

How to resize JqGrid column width

net webform using jqGrid with column Action, Responsible, Target date.
How can i resize the columns. i try to add width:'116' on the column but did not work
i don't have any error on my console
my grid looks like this opon adding
Grid looks
Here's my code on jqgrid
function loadActions(datas) {
// var Responsible = Responsible(),
// Refresh data if jqgrid is already initialized
$('#Actiongrid').jqGrid("GridUnload");
$('#Actiongrid').jqGrid('clearGridData').trigger("reloadGrid");
$('#Actiongrid').jqGrid({
datatype: 'local',
data: datas,
editurl: 'clientArray',
colNames: ['Action','Responsible','TargetDate'],
colModel: [
{ name: 'Batch_no', index: 'Batch_no', sortable: false, editable: true, width:'116' },
{
name: 'Responsible',
index: 'Responsible',
width: '116',
sortable: false,
editable: true,
editrules: { required: true },
edittype: 'select',
editoptions: { value: {} },
},
{
name: 'TargetDate',
width: '116',
index: 'TargetDate',
sortable: false,
editrules: {
required: true,
date: true
},
editable: true,
width: '70px',
align: 'center',
editoptions: {
dataInit: function (el) {
$(el).datepicker({ dateFormat: 'yy-mm-dd' });
},
defaultValue: function () {
var currentTime = new Date();
var month = parseInt(currentTime.getMonth() + 1);
month = month <= 9 ? "0" + month : month;
var day = currentTime.getDate();
day = day <= 9 ? "0" + day : day;
var year = currentTime.getFullYear();
return year + "-" + month + "-" + day;
}
}
},
],
// beforeSelectRow: function (id) {
// if ($('#' + id).attr('editable') == 1) {
// return false;
// }
// },
pager: '#Actiongridpager',
pgbuttons: false,
pginput: false,
sortorder: 'asc',
sortname: 'name',
multiselect: true,
height: '100',
maxheight: '100',
width: '350',
viewrecords: true,
rowNum: 10000
});
$('#Actiongrid').jqGrid({ recreateForm: true })
// Disable form CRUD
$('#Actiongrid').jqGrid('navGrid', '#Actiongridpager', { edit: false, save: false, add: false, cancel: false, del: true, search: false, refresh: false });
// Enable inline CRUD
$('#Actiongrid').jqGrid('inlineNav', '#Actiongridpager', { add: true, edit: true, save: true, cancel: true });
}
What i'm doing wrong or what do i need to add . Hope some help me out with this.
Thank you in advance.

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.

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