There is a concept that eludes me ... I can't figure out what is it I do wrong !!!
I have the following JSON:
{
"data":[
{
"amount":150.00,
"dealDate":"10/18/15 11:53 AM",
"dealName":"Deal 1",
"id":"1",
"parent":"null",
"level":"0",
"isLeaf":false,
"loaded":true
},
{
"amount":100.00,
"dealDate":"10/16/15 11:53 AM",
"dealName":"Deal 1a",
"id":"2",
"parent":"1",
"level":"1",
"isLeaf":true,
"loaded":true
},
{
"amount":-20.34,
"dealDate":"10/16/15 11:53 AM",
"dealName":"Deal 1b",
"id":"3",
"parent":"1",
"level":"1",
"isLeaf":true,
"loaded":true
},
{
"amount":25,
"dealDate":"10/16/15 11:53 AM",
"dealName":"Deal 2",
"id":"4",
"parent":"null",
"level":"0",
"isLeaf":false,
"loaded":true
}
]
}
And the jQgrid definition: (with the treeGrid options removed (commented out))
<script type="text/javascript">
$(function () {
var mydata ;
$.getJSON( "sampleData.json", function( data ) {
mydata=$.extend(true, [], data.data) ;
console.log("Initial JSON data:\n" + JSON.stringify(mydata));
$("#list").jqGrid({
data: mydata,
datatype: "local",
mtype: "GET",
colNames: ["id", "Title", "Amount", "Date", "","","",""],
colModel: [
{ name: "id", width: 55, hidden: true},
{ name: "dealName", width: 90, editable: true },
{ name: "amount", width: 80, align: "right",editable: true },
{ name: "dealDate", width: 80, align: "right", editable: true }
{ name: "parent", width: 80, align: "right", hidden: true },
{ name: "level", width: 80, align: "right", hidden: true },
{ name: "isLeaf", width: 80, align: "right", hidden: true },
{ name: "loaded", width: 80, align: "right", hidden: true }
],
editurl: 'clientArray',
cellsubmit : 'clientArray',
rowNum: 10,
rowList: [10, 20, 30, 50],
sortname: "id",
viewrecords: true,
gridview: true,
// treeGrid: true,
// ExpandColumn: 'dealName',
// treeGridModel:'adjacency',
width: $(window).width() *0.55,
caption: "Deal Test Grid"
});
$("#list").jqGrid('navGrid', "#pager", { edit: false, add: false, del:
false });
$("#list").jqGrid('gridResize');
});
});
</script>
And this produces perfectly fine grid !!
HOWEVER !!!
Once I remove comments from tree grid parameters, my grid is NOT loaded !!
I have tried with adding and with removing of quotes around null value of a parent where there is no parent
"parent":"null", vs. "parent":null,
No avail !! Same results !!
Please, help !! What is it called - that thing that I am doing wrong.
There are some problems in your code. First of all, it's the syntax error in colModel: no comma after the item which defines the column dealDate. The next problem: the input data should contains id, parent, level, isLeaf and isLeaf, but you should not define any columns in colModel with the names. The last important problem: you need include treeGrid: true, treeGridModel: "adjacency", ExpandColumn: "dealName" and optionally ExpandColClick: true to make the grid be TreeGrid.
The resulting code could be
$("#list").jqGrid({
data: mydata,
colNames: ["Title", "Amount", "Date"],
colModel: [
{ name: "dealName", width: 100 },
{ name: "amount", width: 80, template: "number" },
{ name: "dealDate", width: 180, align: "right", sorttype: "date",
formatter: "date",
formatoptions: { srcformat: "n/j/Y g:i A", newformat: "n/j/Y g:i A" } }
],
cmTemplate: { width: 80, autoResizable: true, editable: true },
iconSet: "fontAwesome",
treeGrid: true,
treeGridModel: "adjacency",
ExpandColumn: "dealName",
ExpandColClick: true,
inlineEditing: { keys: true },
ondblClickRow: function (rowid, iRow, iCol, e) {
var $self = $(this), savedRow = $self.jqGrid("getGridParam", "savedRow");
if (savedRow.length > 0 && savedRow[0].id !== rowid) {
$self.jqGrid("restoreRow", savedRow[0].id);
}
$self.jqGrid("editRow", rowid, { focusField: e.target });
}
}).jqGrid("gridResize");
where I included starting inline editing on double-click. The resulting demo can be find here. It uses free jqGrid 4.10.0, which I published today. The code is already available on CDNs (see the wiki article).
Related
I want to use jqgrid with subgrids. I have created a jqgrid table. However, I want to display the descriptions and symbols in the subgrid .
I have also included JSOn data and my code snippet and the fiddle demo here
Can I create subgrids from the following JSON data with jqgrid with out having nested JSON data? Is there any example or demo I can refer to?
$(document).ready(function() {
var jsonData = {
"Name": "Julie Brown",
"Account": "C0010",
"LoanApproved": "12/5/2015",
"LastActivity": "4/1/2016",
"PledgedPortfolio": "4012214.00875",
"MaxApprovedLoanAmt": "2050877.824375",
"LoanBalance": "1849000",
"AvailableCredit": "201877.824375",
"Aging": "3",
"Brokerage": "My Broker",
"Contact": "Robert L. Johnson",
"ContactPhone": "(212) 902-3614",
"RiskCategory": "Yellow",
"rows": [{
"ClientID": "C0010",
"Symbol": "WEC",
"Description": "Western Electric Co",
"ShareQuantity": "20638",
"SharePrice": "21.12",
"TotalValue": "435874.56",
"LTVCategory": "Equities",
"LTVRatio": "50%",
"MaxLoanAmt": "217937.28"
}, {
"ClientID": "C0010",
"Symbol": "BBB",
"Description": "Bins Breakers and Boxes",
"ShareQuantity": "9623",
"SharePrice": "74.29125",
"TotalValue": "714904.69875",
"LTVCategory": "Equities",
"LTVRatio": "50%",
"MaxLoanAmt": "357452.349375"
}, {
"ClientID": "C0010",
"Symbol": "GPSC",
"Description": "Great Plains Small Cap Stock",
"ShareQuantity": "49612",
"SharePrice": "14.24",
"TotalValue": "706474.88",
"LTVCategory": "Mutual Funds - Small Cap",
"LTVRatio": "40%",
"MaxLoanAmt": "282589.952"
}]
},
mmddyyyy = "";
/*********************************************************************/
$("#output").jqGrid({
url: "/echo/json/",
mtype: "POST",
datatype: "json",
postData: {
json: JSON.stringify(jsonData)
},
colModel: [
/** { name: 'ClientID', label:'ClientID',width: 80, key: true },****/
{
name: 'Symbol',
width: 65
}, {
name: 'Description',
width: 165
}, {
name: 'ShareQuantity',
align: 'right',
width: 85,
classes: "hidden-xs", labelClasses: "hidden-xs",
formatter: 'currency',
formatoptions: {
prefix: " ",
suffix: " "
}
}, {
name: 'SharePrice',
label: 'Share Price',
align: 'right',
width: 100,
classes: "hidden-xs", labelClasses: "hidden-xs",
template: "number",
formatoptions: {
prefix: " $",
decimalPlaces: 4
}
},
/*{ label: 'Value1',
name: 'Value1',
width: 80,
sorttype: 'number',
formatter: 'number',
align: 'right'
}, */
{
name: 'TotalValue',
label: 'Total Value',
width: 160,
sorttype: 'number',
align: "right",
formatter: 'currency',
formatoptions: {
prefix: " $",
suffix: " "
}
}, {
name: 'LTVRatio',
label: 'LTV Ratio',
width: 70,
sorttype: 'number',
align: "right",
formatter: 'percentage',
formatoptions: {
prefix: " ",
suffix: " "
}
}, {
name: 'LTVCategory',
label: 'LTV Category',
classes: "hidden-xs", labelClasses: "hidden-xs",
width: 120,
width: 165
},
{
name: 'MaxLoanAmt',
label: 'MaxLoanAmount',
width: 165,
sorttype: 'number',
align: "right",
formatter: 'currency',
formatoptions: {
prefix: " $",
suffix: " "
}
}
],
additionalProperties: ["Num1"],
/*beforeProcessing: function (data) {
var item, i, n = data.length;
for (i = 0; i < n; i++) {
item = data[i];
item.Quantity = parseFloat($.trim(item.Quantity).replace(",", ""));
item.LTVRatio = parseFloat($.trim(item.LTVRatio *10000).replace(",", ""));
item.Value = parseFloat($.trim(item.Value).replace(",", ""));
item.Num1 = parseInt($.trim(item.Num1).replace(",", ""), 10);
item.Num2 = parseInt($.trim(item.Num2).replace(",", ""), 10);
}
}, */
iconSet: "fontAwesome",
loadonce: true,
rownumbers: true,
cmTemplate: {
autoResizable: true,
editable: true
},
autoResizing: {
compact: true
},
autowidth: true,
height: 'auto',
forceClientSorting: true,
sortname: "Symbol",
footerrow: true,
caption: "<b>Collateral Value</b> <span class='pull-right' style='margin-right:20px;'>Valuation as of: " + mmddyyyy + "</span>",
loadComplete: function() {
var $self = $(this),
sum = $self.jqGrid("getCol", "Price", false, "sum"),
sum1 = $self.jqGrid("getCol", "MaxLoanAmt", false, "sum");
//ltvratio = $self.jqGrid("getCol","LTVRatio:addas", "Aved Loan Amount");
$self.jqGrid("footerData", "set", {
LTVCategory: "Max Approved Loan Amount:",
Price: sum,
MaxLoanAmt: sum1
});
}
});
$("#output").jqGrid('filterToolbar', {stringResult: true, searchOnEnter: false, defaultSearch : "cn"});
$(window).on("resize", function () {
var newWidth = $("#output").closest(".ui-jqgrid").parent().width();
$("#output").jqGrid("setGridWidth", newWidth, true);
});
});
If I correctly understand your requirements, it's relatively easy. If you want to display "Symbol" and "Description" in subgrid, then you would like to remove the corresponding columns from the main grid. You use loadonce: true option to fill the local data with the data return from the server. The item, which represent every row of input data, will be filled with columns and the properties from additionalProperties option. Thus you should add
additionalProperties: ["Symbol", "Description"]
after removing "Symbol" and "Description" from the columns.
Now you should add subGrid: true option to create the "subrgid" column with "+" symbol, which allows to open the grid. On opening jqGrid create the div for the subrgid and the callback subGridRowExpanded is responsible to fill the grid with data. One can create subgrid inside of the div, but one can place any HTML fragments in any form. For example
subGridRowExpanded: function (subgridDivId, rowid) {
var item = $(this).jqGrid("getLocalRow", rowid);
$("#" + $.jgrid.jqID(subgridDivId)).html("Symbol: <em>" + item.Symbol +
"</em><br/>Description: <em>" + item.Description + "</em>");
}
The resulting demo https://jsfiddle.net/OlegKi/615qovew/75/ displays the data like on the picture below
You are absolutely free in the design of information displayed in the "subgrid"-div.
I am trying to generate a JQgrid with Subgrid based on examples I came across online but instead of local data, I am using json service .
By Using nested JSON data, where the nested json data is used for the subgrid section.
When I try to create the grid, I keep getting this error "SyntaxError: Unexpected token i in JSON at position 26 200 OK"
What am I doing wrong or missing?
My code is below and my Fiddle is here
MY CODE
$(document).ready(function() {
var jsonData = {
id: 48803,
thingy: "DSK1",
number: "02200220",
status: "OPEN",
subgridData: [{
num: 1,
item: "Item 1",
qty: 3
}, {
num: 2,
item: "Item 2",
qty: 5
}]
},
{
id: 48769,
thingy: "APPR",
number: "77733337",
status: "ENTERED",
subgridData: [{
num: 3,
item: "Item 3",
qty: 5
}, {
num: 2,
item: "Item 2",
qty: 10
}]
},
mmddyyyy = "";
/*********************************************************************/
$("#grid").jqGrid({
url: "/echo/json/",
mtype: "POST",
datatype: "json",
postData: {
json: JSON.stringify(jsonData)
},
height: 'auto',
colNames: ['Inv No', 'Thingy', 'Number', 'Status'],
colModel: [{
name: 'id',
width: 60,
sorttype: "int",
key: true
}, {
name: 'thingy',
width: 90
}, {
name: 'number',
width: 80,
formatter: "integer"
}, {
name: 'status',
width: 80
}],
gridview: true,
autoencode: true,
pager: '#pagerId',
caption: "Stack Overflow Subgrid Example",
subGrid: true,
subGridOptions: {
plusicon: "ui-icon-triangle-1-e",
minusicon: "ui-icon-triangle-1-s",
openicon: "ui-icon-arrowreturn-1-e"
},
shrinkToFit: false,
subGridRowExpanded: function(subgrid_id, row_id) {
var subgrid_table_id = subgrid_id + "_t",
pager_id = "p_" + subgrid_table_id,
localRowData = $(this).jqGrid("getLocalRow", row_id);
$("#" + subgrid_id).html("<table id='" + subgrid_table_id + "'></table><div id='" + pager_id + "'></div>");
$("#" + subgrid_table_id).jqGrid({
datatype: "local",
data: localRowData.subgridData,
colNames: ['No', 'Item', 'Qty'],
colModel: [{
name: "num",
width: 80,
key: true
}, {
name: "item",
width: 130
}, {
name: "qty",
width: 70,
align: "right"
}],
rowNum: 20,
idPrefix: "s_" + row_id + "_",
pager: "#" + pager_id,
autowidth: true,
gridview: true,
autoencode: true,
sortname: "num",
sortorder: "asc",
height: "auto"
}).jqGrid('navGrid', "#" + pager_id, {
edit: false,
add: false,
del: false
});
}
});
});
MY Fiddle
First of all you have to fix the syntax error. The definition of the variable jsonData in the form
var jsonData = {
id: 48803,
...
},
{
id: 48769,
...
};
is false. You try to define jsonData as array of items. Thus the code fragment have to be fixed to
var jsonData = [{
id: 48803,
...
},
{
id: 48769,
...
}];
Then you define <table id="grid"></table>, but create the grid using $("#output").jqGrid({...}); in your demo. You have to use in both cases the same value if id.
Now, back to you main problem. You want to use subgridData property of the items of the data ($(this).jqGrid("getLocalRow", row_id).subgridData) filled via datatype: "json". The datatype: "json" means server based sorting, paging and filtering of the data. jqGrid don't fill local data (the data parameter). To fill data you have to inform jqGrid that the input data from the server contains full data (all the pages) and thus jqGrid should fill data option and to use local sorting, paging and filtering. Thus you should add
loadonce: true,
and
additionalProperties: ["subgridData"],
additionally to inform jqGrid to fill the items of local data with subgridData property together with the properties id, thingy, number and status (the columns of the main grid).
Finally you can remove unneeded pager divs and to use simplified form of the pager: pager: true. You should consider to use Font Awesome additionally: iconSet: "fontAwesome".
The modified demo is https://jsfiddle.net/OlegKi/615qovew/64/, which uses the following code
$(document).ready(function() {
var jsonData = [{
id: 48803,
thingy: "DSK1",
number: "02200220",
status: "OPEN",
subgridData: [{
num: 1,
item: "Item 1",
qty: 3
}, {
num: 2,
item: "Item 2",
qty: 5
}]
},
{
id: 48769,
thingy: "APPR",
number: "77733337",
status: "ENTERED",
subgridData: [{
num: 3,
item: "Item 3",
qty: 5
}, {
num: 2,
item: "Item 2",
qty: 10
}]
}],
mmddyyyy = "",
$grid = $("#output");
/*********************************************************************/
$grid.jqGrid({
url: "/echo/json/",
mtype: "POST",
datatype: "json",
postData: {
json: JSON.stringify(jsonData)
},
colNames: ['Inv No', 'Thingy', 'Number', 'Status'],
colModel: [{
name: 'id',
width: 60,
sorttype: "int",
key: true
}, {
name: 'thingy',
width: 90
}, {
name: 'number',
width: 80,
formatter: "integer"
}, {
name: 'status',
width: 80
}],
loadonce: true,
additionalProperties: ["subgridData"],
autoencode: true,
pager: true,
caption: "Stack Overflow Subgrid Example",
subGrid: true,
/*subGridOptions: {
plusicon: "ui-icon-triangle-1-e",
minusicon: "ui-icon-triangle-1-s",
openicon: "ui-icon-arrowreturn-1-e"
},*/
iconSet: "fontAwesome",
shrinkToFit: false,
subGridRowExpanded: function(subgridDivId, rowid) {
var $subgrid = $("<table id='" + subgridDivId + "_t'></table>"),
subgridData = $(this).jqGrid("getLocalRow", rowid).subgridData;
$("#" + subgridDivId).append($subgrid);
$subgrid.jqGrid({
data: subgridData,
colNames: ['No', 'Item', 'Qty'],
colModel: [{
name: "num",
width: 80,
key: true
}, {
name: "item",
width: 130
}, {
name: "qty",
width: 70,
align: "right"
}],
rowNum: 20,
idPrefix: "s_" + rowid + "_",
pager: true,
iconSet: "fontAwesome",
autowidth: true,
autoencode: true,
sortname: "num"
}).jqGrid('navGrid', {
edit: false,
add: false,
del: false
});
}
}).jqGrid('filterToolbar', {
stringResult: true,
searchOnEnter: false,
defaultSearch: "cn"
});
$(window).on("resize", function() {
var newWidth = $grid.closest(".ui-jqgrid").parent().width();
$grid.jqGrid("setGridWidth", newWidth, true);
}).triggerHandler("resize");
});
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.
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.
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.