JqGrid give ID when button pressed - javascript

I cant select any rows in my JqGrid so I came across http://www.jqgrid.com/jqgrid/forum/codemerx-jqgrid-for-asp-net/146-can-t-select-rows. Which says I need a ID for every row. I add data to my Grid each time I press a button. I tried giving each row a id with a simple click counter function. But then I when I try to sort all ID's dissapear from the Grid.
Any suggestion how I can solve this?
Grid
$(document).ready(function () {
// Configuration for jqGrid Example 1
$("#table_list_1").jqGrid({
data: currentTime,
datatype: "local", //if enabled id dissapear
height: "100%",
autowidth: true,
shrinkToFit: true,
loadonce: true,
sortable: true,
rowNum: 100,
rownumbers: true,
rowList: [10, 20, 30],
colNames: ['Id','Time', 'Note'], // 'Id'
colModel: [
{name: 'id', index:'id', width:60, sorttype: 'number', sortable: true},
{ name: 'time', index: 'time', width: 60, sorttype: 'number', sortable: true, editable: true, formatter: "number" },
{ name: 'note', index: 'note', width: 60, cellEdit: true, editable: true }
],
pager: "#pager_list_1",
viewrecords: true,
caption: "Example jqGrid 1",
add: true,
edit: true,
addtext: 'Add',
edittext: 'Edit',
hidegrid: false
});
$('#table_list_1').navGrid('#pager_list_1',
{ edit: false, add: false, del: false, search: true, refresh: true, view: false, position: "left", cloneToTop: true },
{ reloadAfterSubmit: true });
$('#table_list_1').navButtonAdd('#pager_list_1',
{
buttonicon: "ui-icon-pencil",
title: "Edit",
caption: "",
position: "last",
});
How I add data
var currentTime = [];
var id = 0;
function doKeyDown(e) {
//test document.getElementById("currentTimeText").innerHTML = currentTime;
if (e.keyCode == 49 & wavesurfer.isPlaying()) {
// KEY = " 1 "
id += 1;
currentTime.push(wavesurfer.getCurrentTime());
jQuery("#table_list_1").addRowData("", { id: id, time: wavesurfer.getCurrentTime() });
//test document.getElementById("currentTimeText").innerHTML = currentTime;
wavesurfer.addRegion({
start: wavesurfer.getCurrentTime(),
end: wavesurfer.getCurrentTime() + 0.1,
color: '#19aa8d',
resize: false,
drag: false,
});
}
}

The rowid is not the value from id property, but the first parameter which you use with the same "" value. I think it's the main bug in your code. The call
jQuery("#table_list_1").addRowData("", { id: id, time: wavesurfer.getCurrentTime() });
should be fixed at least to
jQuery("#table_list_1").addRowData(undefined, { id: id, time: wavesurfer.getCurrentTime() });

Solved it like this:
jQuery("#table_list_1").addRowData(id, { id: id, time: wavesurfer.getCurrentTime() });
So instead of "undefined" I just gave it "id"
This solved my select problem too.

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.

How to get the particular cell value in JQgrid

I have written a JQGrid which was working fine but I need to fill the sub grid based on the selected row of main grid. How can I get the selected row cell value to pass in the url of subgrid.
columns in the main grid ---- Id,Firstname,Lastname,Gender.
I need to get selected row of "Id" value.
Here is my script
$(document).ready(function () {
jQuery("#EmpTable").jqGrid({
datatype: 'json',
url: "Default1.aspx?x=getGridData",
mtype: 'POST',
ajaxGridOptions: { contentType: 'application/json; charset=utf-8' },
serializeGridData: function (postData) {
return JSON.stringify(postData);
},
jsonReader: { repeatitems: false, root: "rows", page: "page", total: "total", records: "records" },
colNames: ['PID', 'First Name', 'Last Name', 'Gender'],
colModel: [
{ name: 'PID', width: 60, align: "center", hidden: true, searchtype: "integer", editable: true },
{ name: 'FirstName', width: 180, sortable: true, hidden: false, editable: true, sorttype: 'string', searchoptions: { sopt: ['eq', 'bw']} },
{ name: 'LastName', width: 180, sortable: false, hidden: false, editable: true },
{ name: 'Gender', width: 180, sortable: false, hidden: false, editable: true, cellEdit: true, edittype: "select", formater: 'select', editrules: { required: true, edithidden: true }, editoptions: { value: getAllSelectOptions()}}],
loadonce: true,
pager: jQuery('#EmpPager'),
rowNum: 5,
rowList: [5, 10, 20, 50],
viewrecords: true,
sortname: 'PID',
sortorder: "asc",
height: "100%",
editurl: 'Default1.aspx?x=EditRow',
subGrid: true,
// subGridUrl: 'Default1.aspx?x=bindsubgrid',
subGridRowExpanded: function (subgrid_id, row_id) {
// var celValue = jQuery('#EmpTable').jqGrid('getCell', rowId, 'PID');
var subgrid_table_id, pager_id;
subgrid_table_id = subgrid_id + "_t";
pager_id = "p_" + subgrid_table_id;
$("#" + subgrid_id).html("");
jQuery("#" + subgrid_table_id).jqGrid({
url: "Default1.aspx?x=bindsubgrid&PID=" + row_id + "",
datatype: "json",
mtype: 'POST',
ajaxGridOptions: { contentType: 'application/json; charset=utf-8' },
serializeGridData: function (postData) {
return JSON.stringify(postData);
},
jsonReader: { repeatitems: false, root: "rows", page: "page", total: "total", records: "records" },
colNames: ['PID', 'First Name', 'Last Name', 'Gender'],
colModel: [
{ name: 'PID', width: 60, align: "center", hidden: true, searchtype: "integer", editable: true },
{ name: 'FirstName', width: 180, sortable: true, hidden: false, editable: true, sorttype: 'string', searchoptions: { sopt: ['eq', 'bw']} },
{ name: 'LastName', width: 180, sortable: false, hidden: false, editable: true },
{ name: 'Gender', width: 180, sortable: false, hidden: false, editable: true, cellEdit: true, edittype: "select", formater: 'select', editrules: { required: true, edithidden: true }, editoptions: { value: getAllSelectOptions()}}],
loadonce: true,
rowNum: 5,
rowList: [5, 10, 20, 50],
pager: pager_id,
sortname: 'PID',
sortorder: "asc",
height: '100%'
});
jQuery("#" + subgrid_table_id).jqGrid('navGrid', "#" + pager_id, { edit: false, add: false, del: false })
}
})
Please help to find the cell value.
Thanks
purna
If 'PID' column contains unique value which can be used as the rowid then you should add key: true in the definition of the 'PID' column in colModel. jqGrid will assign id attribute of <tr> elements (the rows of the grid) to the value from 'PID' column. After that row_id parameter of subGridRowExpanded will contain the value which you need and you will don't need to make any additional getCell call.
Additional remark: I strictly recommend you to use idPrefix parameter for subgrids and probably for the grids. In the case jqGrid will use the value of id attribute which have the specified prefix. If will allow to solve conflicts (id duplicates in HTML page). Currently you can have the same rowids for the rows of subgrids and to the rows of the main grid. See here more my old answers on the subject.

Load Editable JQgrid with dynamic data

I'm loading the JQgrid from the external Ajax call. I'm expecting my JQgrid to set the values with the edit fields once i pass my Array object.
I have tried all the ways which i found in google, but no luck.
Can someone point me where i'm making mistake ?
var grid = $("#JobGrid").jqGrid({
datatype: "json",
colNames: ['Product Name', 'Product ID', 'ProdTypeAvail', 'Piece/Sheet', 'Type', 'Pages', 'Copies', 'ExtraCharges', '', ''],
colModel: [
{ name: 'strProductName', index: 'strProductName', editable: true, edittype: 'text' },
{ name: 'strProductID', index: 'strProductID', editable: true, hidden: true, editrules: { edithidden: true } },
{ name: 'strProdTypeAvail', index: 'strProdTypeAvail', editable: true, hidden: true, editrules: { edithidden: true } },
{ name: 'iPiecesPerSheet', index: 'ipieces', editable: true, edittype: 'text', formatter: TrimZero },
{ name: 'strProductType', index: 'strProducttype', editable: true, edittype: 'select' },
{ name: 'iPages', index: 'iPages', editable: true, edittype: 'text', formatter: TrimZero },
{ name: 'iCopies', index: 'iCopies', editable: true, edittype: 'text', formatter: TrimZero },
{ name: 'dExtraCharge', index: 'dExtraCharge', editable: true, edittype: 'text', formatter: TrimZero },
{
name: 'Delete', label: 'Delete', title: 'Delete', width: 25, index: 'Delete', sortable: false,
formatter: function () {
return "<input type='button' value='del' />"
//return "<div><img src='http://icons.iconarchive.com/icons/hopstarter/button/16/Button-Delete-icon.png'/></div>"
}
},
{
name: 'Duplicate', width: 25, index: 'Duplicate', sortable: false,
formatter: function () {
return "<input type='button' value='dup' />"
//return "<div><img src='http://icons.iconarchive.com/icons/hopstarter/soft-scraps/16/File-New-icon.png'/></div>"
}
}
],
hidegrid: false,
autowidth: true,
shrinkToFit: true,
height: '100%',
scrollOffset: 0,
rowNum: -1,
jsonReader: { repeatitems: false},
rownumbers: true,
caption: "Job Details",
cellEdit: true,
cellsubmit: 'clientArray',
editurl: 'clientArray',
pager: '#JobGridpager',
localReader: { id: 'iRowID' },
....
My AJAX Call to load JQgrid
$j("#txtJobID").change(function () {
....
$j.ajax({
type: 'GET',
url: "http:/localhost:20/api/Job/GetFullJobDetails?Ary=" + JSON.stringify(obj),
dataType: 'json',
success: function (oJobdata) {
var oData = oJobdata.lstJobChildInfo;
grid.jqGrid('clearGridData');
grid.setGridParam({ data: oData });
grid[0].refreshIndex();
grid.trigger("reloadGrid");
...
My "oData" which I'm passing to my JQgrid...
[object1, object2]
Object1 :
dExtraCharge: 10
dJobDate: "0001-01-01T00:00:00"
iAddCopy: 0
iCopies: 4
iFirstCopy: 0
iPages: 1
iPiecesPerSheet: 0
iRowID: 1
iTotalCopy: 0
lstJobChildInfo: null
strAction: null
strCompanyID: "C01"
strCustomerID: null
strCustomerName: null
strJobID: null
strJobchdid: null
strMobile: null
strProdTypeAvail: "PT01-PT02-PT03"
strProductID: "P005"
strProductName: "Art 130 +3"
strProductType: "One Side"
strProductTypeID: "PT01"
strStatus: null
strUserName: null
proto: Object
Object2 :
dExtraCharge: 0
dJobDate: "0001-01-01T00:00:00"
iAddCopy: 0
iCopies: 4
iFirstCopy: 0
iPages: 2
iPiecesPerSheet: 2
iRowID: 2
iTotalCopy: 0
lstJobChildInfo: null
strAction: null
strCompanyID: "C01"
strCustomerID: null
strCustomerName: null
strJobID: null
strJobchdid: null
strMobile: null
strProdTypeAvail: "PT01-PT02-PT03"
strProductID: "P023"
strProductName: "Synthetic 125 Micron"
strProductType: "Diff Front And Back"
strProductTypeID: "PT02"
strStatus: null
strUserName: null
proto: Object
I have try setting,
iRowID as ID
jsonReader: { repeatitems: false},
grid[0].refreshIndex();
but still grid remains empty without any data :-(

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.

Categories

Resources