Remove horizontal scrollbar from jqGrid - javascript

Hi I have responsive UI where I am using a jqGrid. In this, when I open it in full-screen the grid works fine. Now, when I try to resize it, horizontal scrollbar comes.
Like this
Now, I referred the internet there are different solutions for this problem and I tried almost whatever I have got my hand on.
I have tried this link jqGrid horizontal scrollbar
But here it hides the last columns
I have checked this also - JQGrid How do I removed the annoying horizontal scrollbar when autowidth = true? (In IE) but this was not my case
I have checked this link also - How to get rid of horizontal scroll bar when not needed
And the new one where we are getting rid of scrollbar in chrome
jqGrid does not render correctly in Chrome/Chrome Frame
I have considered this also -
http://www.trirand.com/blog/?page_id=393/help/horizontal-scrollbar
I have applied following properties -
shrinkToFit: true,
autowidth:true
My css properties are
.ui-jqgrid {
max-width: 100% !important; width: auto !important;}
.ui-jqgrid .ui-jqgrid-pager {
width: auto !important;
}
.ui-jqgrid-bdiv {
overflow-y: scroll !important;
}
.ui-jqgrid-view,.ui-jqgrid-hdiv,.ui-jqgrid-bdiv {
width: auto !important;
}
.ui-th-ltr, .ui-jqgrid .ui-jqgrid-htable th.ui-th-ltr {
text-align:center;
font-style:normal;
}
.ui-th-ltr, .ui-jqgrid .ui-jqgrid-htable th.ui-th-ltr > em {
font-style: normal;
}
I have tried this solution also
.ui-jqgrid .ui-jqgrid-btable
{
table-layout:auto;
}
I have also commented out this-
.ui-widget :active { outline: none; }
Note: I am using IE 11. I want jqGrid to everytime it should calculate the width when user resize the screen so that there will not be horizontal scrollbar
EDITED : I ma using license jqGrid 4.1.2. Its a free version only.
Also, I am using a function here which resize according to browser window
/* Resize grid on browser window */
function resizeJqGridWidth(grid_id, div_id, width) {
var cnt = 0;
$(window).bind('resize', function () {
}).trigger('resize');
}
and I am calling it like
resizeJqGridWidth(grid_id, "gview_" + grid_id, "90%");
My code :
var grid_data = data,
grid = $("#" + grid_id);
grid.jqGrid({
datatype: "jsonstring",
datastr: grid_data,
colNames: scopes.grid_header_column_value,
colModel: scopes.gridcolumns,
height: height,
//gridview: true,
loadonce: true,
viewrecords: is_pager_enable,
rowList: row_list,
rowNum: row_number,
multiSort: true,
ignoreCase: true,
grouping: is_group_enable,
sortorder: sort_order,
cmTemplate: { autoResizable: true },
autoresizeOnLoad: true,
autoResizing: { compact: true, resetWidthOrg: true },
sortable: false,
pager: "#" + pager_id,
treeGrid: true,
treeGridModel: 'adjacency',
treedatatype: "local",
ExpandColumn: 'name',
// sortname: 'name',
jsonReader: {
repeatitems: false,
root: function (obj) { return obj; },
page: function () { return 1; },
total: function () { return 1; },
records: function (obj) { return obj.length; },
expanded_field: "true"
},
gridComplete: function () {
$("#" + grid_id+"count").html($("#" + grid_id).getGridParam('records')+" row(s)");
},
loadComplete: function () {
var ts = this;
//document.querySelector('#filterbutton').addEventListener('onclick', clickqw);
if (ts.p.reccount === 0) {
$(this).hide();
emptyMsgDiv.show();
} else {
$(this).show();
emptyMsgDiv.hide();
}
}
});
Added code for opening popup - Here I used to call a funtion getPopup which is then do necessary thing to load a modal window.
if (formatter == "Link") {
var subpopup = grid_row_data[j]._attr.popupid._value;
var xmlname = grid_row_data[j]._attr.popxml._value;
formatter= 'dynamicLink';
formoption= {
url: function (cellValue, rowId, rowData) {
return '/' + rowId + '?' + $.param({
tax: rowData.col_nigo,
invdate: rowData.col_klo,
closed: rowData.col_phq
});
},
cellValue: function (cellValue, rowId, rowData) {
return '<span class="pointer">' + cellValue + '</span>';
},
onClick: function (rowId, iRow, iCol, cellValue, e) {
$("#"+subpopup).css("display", "block");
$("#" + popupid).css("opacity", "0.99");
$scope.getPopup(rowId, iRow, iCol,gridid ,xmlname,rowId);
}
};
cellattr = function (rowId, cellValue, rawObject) {
var attribute = ' title="' + rawObject.name;
if (rawObject.closed) {
attribute += ' (closed)';
}
return attribute + '"';
};
}
}

Related

kendo Grid excelExport's hideColumn not working

I am trying to hide one column from excelExport. I have tried some traditional ways shown on google like e.sender.hideColumn(13) or e.sender.hideColumn("bID") or grid.hideColumn(13). but none of this working for me. I have also done exportPDF which is working perfectly.
here is JS code I am attaching, to show what I am doing.
$("#ALReport").kendoGrid({
toolbar: ["excel", "pdf"],
excel: {
allPages: true,
fileName: "ALReport" + todayDateFormatted() + ".xlsx",
proxyURL: "/content",
filterable: true
},
excelExport: function (e) {
e.sender.hideColumn(12);
var grid = $("#ALReport").data("kendoGrid");
grid.hideColumn("Bid");
},
pdf: {
allPages: true,
filterable: true,
fileName: "ALReport" + todayDateFormatted() + ".pdf",
proxyURL: "/content",
margin: {
left: 10,
right: "10pt",
top: "10mm",
bottom: "1in"
}
},
pdfExport: function (e) {
var grid = $("#ALReport").data("kendoGrid");
grid.hideColumn("Bid");
$(".k-grid-toolbar").hide();
e.promise
.done(function () {
grid.showColumn("Bid");
$(".k-grid-toolbar").show();
});
},
dataSource: {
serverSorting: true,
serverPaging: true,
transport: {
read: getActionURL() + "ALReport....
},
.....
This is my js code. Can anyone guide where i am making mistake?
Your export to excel has no effect because event is fired after all data have been collected. For your example try following approach:
var exportFlag = false;
$("#grid").kendoGrid({
toolbar: ["excel", "pdf"],
excel: {
allPages: true,
fileName: "ALReport" + todayDateFormatted() + ".xlsx",
proxyURL: "/content",
filterable: true
},
excelExport: function (e) {
if (!exportFlag) {
e.sender.hideColumn("Bid");
e.preventDefault();
exportFlag = true;
setTimeout(function () {
e.sender.saveAsExcel();
});
} else {
e.sender.showColumn("Bid");
exportFlag = false;
}
}
For this example event is prevented and fired one more time excluding hidden column.

Filter toolbar not coming in jqGrid

I am using free jqGrid 4.14. I am having trouble in displaying filter toolbar in the grid. I am using the same code that I was using to display filter toolbar in version 4.1.2
but here the toolbar is not appearing.
I need the toolbar to display only when filter image is clicked in the grid otherwise it should hide. So, I am using the below code for that in previous version but here in new the same is
not working
grid.jqGrid({
datatype: "jsonstring",
datastr: grid_data,
colNames: scopes.grid_header_column_value,
colModel: scopes.gridcolumns,
height: height,
viewrecords: is_pager_enable,
multiSort: true,
ignoreCase: true,
grouping: is_group_enable,
sortorder: sort_order,
sortable: false,
pager: "#" + pager_id,
treeGrid: true,
treeGridModel: 'adjacency',
treedatatype: "local",
ExpandColumn: 'name',
gridComplete: function () {
$("#" + grid_id+"count").html($("#" + grid_id).getGridParam('records')+" row(s)");
},
beforeSelectRow: function (rowid, e) {
var item = $(this).jqGrid("getLocalRow", rowid);
if (item != null && item.isLeaf) {
$("#"+$rootScope.subpopup).css("display", "block");
$scope.getPopup($rootScope.xmlname,grid_id,rowid);
}
return true; // allow row selection
},
loadComplete: function () {
var ts = this;
//document.querySelector('#filterbutton').addEventListener('onclick', clickqw);
if (ts.p.reccount === 0) {
$(this).hide();
emptyMsgDiv.show();
} else {
$(this).show();
emptyMsgDiv.hide();
}
}
});
grid.jqGrid('filterToolbar', { stringResult: true, searchOnEnter: false, defaultSearch: "cn", searchOperators: true }).navGrid("#" + pager_id, { edit: false, add: false, del: false, refresh: true, search: false });
Here I am hiding or showing the bar on need basis
var count = 1;
grid.closest("div.ui-jqgrid-view").find("div.ui-jqgrid-hdiv table.ui-jqgrid-htable tr.ui-jqgrid-labels > th.ui-th-column > div.ui-jqgrid-sortable > button.btnfilter ")
.each(function () {
$('<button>').css({ height: '10px',background: 'url(img/filter.png) no-repeat',border: '0'
}).appendTo(this).button({
icons: {
primary: ""
},
text: false
}).click(function (e) {
var idPrefix = "jqgh_" + grid[0].id + "_",
thId = $(e.target).closest('div.ui-jqgrid-sortable')[0].id;
if (thId.substr(0, idPrefix.length) === idPrefix) {
if (count == 1) {
$('#gview_' + grid_id).find("div.ui-jqgrid-hdiv table.ui-jqgrid-htable tr.ui-search-toolbar").show();
count = 0;
}
else {
$('#gview_' + grid_id).find("div.ui-jqgrid-hdiv table.ui-jqgrid-htable tr.ui-search-toolbar").hide();
count = 1;
}
return false;
}
});
});
$('#gview_' + grid_id).find("div.ui-jqgrid-hdiv table.ui-jqgrid-htable tr.ui-search-toolbar").hide();
EDIT : Adding the images
This is when image where there the filter is not applied. Only the image (funnel image) for filter where the filter can be applied is shown.
Here when we click on the image of filter only then the filtertoolbar should appear.

JQGrid empty grid and no navigation or edit icons

For some reason, my grid is blank with no rows (not even an empty row), no navigation icons and no editing icons. I'm using a few add-in features such as an autocomplete field (inside the grid), and a font resizing script so my script is a bit long. The page is receiving the properly formatted response from my functions page and it seems to match my jsonReader settings but it's not populating the grid with it. Here is my JSON formatted response from the page:
{"page":"1",
"total":1,
"records":"4",
"rows":[{"DetailID":"1","Quantity":"2","TaskName":"Differencial With Housing","UnitPrice":"335.00","ExtendedPrice":"670.00"}, {"DetailID":"2","Quantity":"1","TaskName":"Left axel seal","UnitPrice":"15.00","ExtendedPrice":"15.00"},{"DetailID":"3","Quantity":"1","TaskName":"Upper and Lower Bearings","UnitPrice":"55.00","ExtendedPrice":"55.00"}, {"DetailID":"5","Quantity":"1","TaskName":"Fluids","UnitPrice":"45.00","ExtendedPrice":"45.00"}]}
And here is my grid script:
<script>
function autocomplete_element(value, options) {
var $ac = $('<input type="text"/>');
$ac.val(value);
$ac.autocomplete({source: "autocomplete.php?method=fnAutocomplete"});
return $ac;
}
function autocomplete_value(elem, op, value) {
if (op == "set") {
$(elem).val(value);
}
return $(elem).val();
}
$(document).ready(function()
{
$('#filter').jqm();
var selectedRow = 0;
$("#list").jqGrid(
{
url:'managegrid.php',
datatype: 'json',
colNames:['DetailID', 'ProjectID','Qty.','Description','Unit Price','Total Cost'],
colModel :[
{name:'DetailID', index:'DetailID', hidden:true, editable:false},
{name:'ProjectID', index:'ProjectID', width:25, hidden:true, editable:true},
{name:'Quantity', index:'Quantity', editable:true, width:50, align:'right', edittype:'text', editoptions: {defaultValue:'1'}},
{name:'TaskName', index:'TaskName', editable:true, width:450, align:'left', edittype: 'custom', editoptions: {'custom_element' : autocomplete_element, 'custom_value' : autocomplete_value}},
{name:'UnitPrice', index:'UnitPrice', editable:true, width:100, align:'right'},
{name:'ExtendedPrice', index:'ExtendedPrice', editable:false, width:100, align:'right'}
],
onSelectRow: function(id){
if(DetailID && DetailID!==mkinline){
jQuery('#list').saveRow(mkinline);
jQuery('#list').editRow(DetailID,true);
mkinline=DetailID;
}
},
pager: $('#pager'),
rowNum:20,
rowList:[],
pgbuttons: false,
pgtext: null,
sortorder: "asc",
sortname: "DetailID",
viewrecords: true,
imgpath: '/js/jquery/css/start/images',
caption: 'Project Details',
height:'auto',
width:823,
mtype:'GET',
recordtext:'',
pgtext:'',
editurl:"editgrid.php",
toolbar:[true,"bottom"],
loadComplete:function(){
var recorddata = $("#list").getUserData();
$("#t_list").html(recorddata.MSG);
},
jsonReader: {
page: "PAGE",
total: "TOTAL",
records:"RECORDS",
root: "ROWS",
userdata:"USERDATA"
}
}
);
$("#t_list").css("color","blue");
jQuery("#list").jqGrid("inlineNav",'#pager',{edit:true,editicon: "ui-icon-pencil",add:true,addicon: "ui-icon-plus",search:false}, {}, {},
{url:"delgridrow.php",closeAfterDelete:true,reloadAftersubmit:false,afterSubmit:commonSubmit,caption:"Delete",msg:"Delete selected",width:"400"})
.navButtonAdd('#pager',{caption:"",title:"Reload Form",buttonimg:'/js/jquery/css/start/images/refresh.gif',onClickButton:function(id)
{
resetForm();
$("#list").setGridParam(
{
url:"managegrid.php",
page:1
}
).trigger("reloadGrid");
}
});
}
);
function gridSearch()
{
var pid = $("#DetailID").val();
var qty = $("#Quantity").val();
var tn = $("#TaskName").val();
var up = $("#UnitPrice").val();
$("#list").setGridParam(
{
url:"managegrid.php?ProjectID="+pid+"&Quantity="+qty+"&TaskName="+tn+"&UnitPrice="+up,
page:1
}
).trigger("reloadGrid");
$("#filter").jqmHide();
return false
}
function commonSubmit(data,params)
{
var a = eval( "(" + data.responseText + ")" );
$("#t_list").html(a.USERDATA.MSG);
resetForm();
return true;
} function resetForm()
{
window.location.reload(false);
}
</script>
I've been trying to figure this one out all weekend and it's driving me crazy so any help would be appreciated.
You should add the line of code
jQuery("#list").jqGrid("navGrid", '#pager',
{add: false, edit: false, del: false, search: false, refresh: false});
directly before calling of inlineNav.
UPDATED: Your code have many other problems too. For example, you should remove jsonReader option from your code, because it contains wrong values of properties (like root: "ROWS" instead of root: "rows", which is default and can be removed). You can consider to use jsonReader: { id: 'DetailID' } to use the value of DetailID as the rowid and to use DetailID instead of id during editing. I'd recommend you to define all variables before the usage (see mkinline and DetailID for example).

free-jqGrid search button does not work on second click

The search button works on the first click, but once it is closed either by clicking the X (close button) or by running a search (setting to close after search) it does not open, there are also no errors in the console so I am unable to determine what is wrong and how to fix it.
var previouslySelectedRow = null;
var rowIsSelected = null;
var previousRowIsSelected = null;
var currentRowId;
var currentCount;
var cancelEditing = function(theGrid) {
var lrid;
if (typeof previouslySelectedRow !== "undefined") {
// cancel editing of the previous selected row if it was in editing state.
// jqGrid hold intern savedRow array inside of jqGrid object,
// so it is safe to call restoreRow method with any id parameter
// if jqGrid not in editing state
theGrid.jqGrid('restoreRow', previouslySelectedRow);
// now we need to restore the icons in the formatter:"actions"
lrid = $.jgrid.jqID(previouslySelectedRow);
$("tr#" + lrid + " div.ui-inline-edit").show();
$("tr#" + lrid + " div.ui-inline-save, " + "tr#" + lrid + " div.ui-inline-cancel").hide();
}
};
var parsedResult = JSON.parse(DecodeAscii(result));
ShowDebugNotification("DEBUG INFO(" + ajaxCall + "): <br />" + result, false);
$("#productsTable").jqGrid({
data: parsedResult,
datatype: "local",
loadonce: true,
height: 'auto',
marginLeft: 'auto',
colNames: [
'Product Id', 'Add', 'Product Name', 'Product Code', 'Customer Price'
],
colModel: [
{ name: 'Id', width: 0, hidden:true },
{ name: "actions", template: "actions", width: 50, formatoptions:{
delbutton: false,
editbutton: false
} },
{ name: 'Name', index: 'Name', width: 550, search: true, searchoptions:{sopt:['eq','bw','bn','cn','nc','ew','en']} },
{ name: 'ProductCode', index: 'ProductCode', width: 150, search: true, searchoptions:{sopt:['eq','bw','bn','cn','nc','ew','en']} },
{ name: 'Price', index: 'Price', width: 100, search: false, formatter: 'currency', formatoptions:{decimalSeparator:".", thousandsSeparator: ",", decimalPlaces: 2, prefix: "$"}}
],
rowNum: 15,
rowList: [5, 10, 15, 20],
pager: true,
gridView: true,
viewrecords: true,
iconSet: "jQueryUI",
sortname: 'Name',
sortorder: 'asc',
inlineEditing: { keys: false },
actionsNavOptions: {
addToCarticon: "ui-icon-cart",
addToCarttitle: "Add item to the cart",
custom: [
{ action: "addToCart", position: "first", onClick: function (options) {
var rowData = $('#productsTable').getRowData(options.rowid);
var cartButton = $(".ui-icon", "#jAddToCartButton_"+options.rowid);
if(cartButton.hasClass("ui-icon-cancel")){
cart.shift(rowData);
cartButton.removeClass("ui-icon-cancel");
cartButton.addClass("ui-icon-cart");
}
else if(cartButton.hasClass("ui-icon-cart")){
cart.push(rowData);
cartButton.removeClass("ui-icon-cart");
cartButton.addClass("ui-icon-cancel");
}
}
}]
},
loadComplete: function() {
$("#add-product-dialog-loading-message").hide();
$(".spinner").hide();
$("#add-product-dialog-form").dialog("open");
//for each object in cart
//if prodcut ID matches product Id in product
//grid then set button to a cancel icon
if(cart.length !== 0){
var cartIds = [];
var jsonCart = JSON.stringify(cart);
var parsedJsonCart = JSON.parse(jsonCart);
var productsInCart = $.grep(parsedJsonCart, function(el, i){
cartIds.push(el.Id);
});
var currentRows = $('#productsTable').getRowData();
var shownProductsThatAreInCart = $.grep(currentRows, function (el, i) {
return $.inArray(el.Id, cartIds) !== -1;
});
if(shownProductsThatAreInCart.length > 0){
var rowIds = $(this).jqGrid('getDataIDs');
$.each(rowIds, function(k, v) {
rowData = $('#productsTable').getRowData(v);
if($.inArray(rowData['Id'], cartIds) !== -1){
alert("Matched Product:\nRowData['id'] = " + rowData['Id'] + "\nto\nProduct in cart: " + cartIds.Id);
$(".ui-icon", "#jAddToCartButton_"+v).removeClass("ui-icon-cart");
$(".ui-icon", "#jAddToCartButton_"+v).addClass("ui-icon-cancel");
}
});
}
}
},
gridComplete: function() {
}
});
$("#productsTable").jqGrid("navGrid", {edit:false,add:false,del:false},
{},// use default settings for edit
{},// use default settings for add
{},// delete instead that del:false we need this
{multipleSearch:false,overlay:false,ignoreCase:true,closeAfterSearch:true,closeOnEscape:true,showQuery:true});
I don't think its a bug as I have seen many demos demonstrating how it is supposed to work, I am guessing I have a mis-configuration, please have a look over my code and help determine the issue.
One thing to keep in mind is I am getting the data to load the grid via an ajax call that returns json, all manipulation is done on the client, there is no posting data back to server at all.
Thank you!
The main problem is the combination of Searching options which you use:
{
multipleSearch: false, // it's default and can be removed
overlay: false, // !!! the option make the problem
ignoreCase: true, // it's not exist at all
closeAfterSearch: true,
closeOnEscape: true,
showQuery: true
}
The usage of the option overlay: false is bad because it makes another option toTop: true not working and the Searching dialog will be placed as the children of jQuery UI Dialog. If you remove the option then one can work with the Searching Dialog more easy and the second problem (a bug in calculation of position of jqGrid Searching Dialog) will not exist. Look at the modified demo:
https://jsfiddle.net/OlegKi/su7mf5k9/3/
UPDATED: It seems one have the problem in creating modal jqGrid dialog inside of modal jQuery UI dialog. The problem could be solved by removing modal: true option from the outer jQuery UI dialog. See https://jsfiddle.net/OlegKi/su7mf5k9/3/
In general one could create hybrid solution which changes the type of jQuery UI dialog from modal to non-modal dynamically, but it could be tricky https://jsfiddle.net/OlegKi/su7mf5k9/5/

Unable to sort jqGrid column with sorttype function

Trying to sort a grid with custom sort. I am building jqgrid with dynamic columns and data. Everything works well except sorting of one of the column. I am using javax.json to build the json and I am using jqgrid 4.7.0. Here is the grid code:
var resultsGrid = $("#resultsGrid");
var url = "grid/GridDataController?action=runSearch&searchText="+getSearchText()+"&_ts"+$.now();
var csvUrl = "grid/GridDataController?action=downloadCsv&_ts"+$.now();
var gridPagerId="#resultsPager";
var drawSearchResultsGrid = function(colNames,colModel,data) {
resultsGrid.disableSelection(); //disales highlioghting cells outside selection like ghosting.
resultsGrid.jqGrid({
url: url,
datatype: 'jsonstring',
loadonce: true,
mtype: "GET",
height: 300,
width: 700,
colNames: colNames,
colModel: colModel,
datastr : data,
rowNum: 100000,
sortname: "invid",
sortorder: "asc",
rownumbers: true,
viewrecords: true,
pager: gridPagerId,
pginput : false,
pgbuttons : false,
viewrecords : false,
gridview: true,
autoencode: true,
onSelectRow : function(id) {
logMessage("row selected ["+id+"]");
},
loadComplete: function(data) {
logMessage("load completed");
},
ondblClickRow : function(rowid) {
logMessage("Double clicked");
$(escapeColon("#contentForm:viewPropertiesButton")).click();
}
});
// Set navigator with search enabled.
resultsGrid.jqGrid('navGrid',gridPagerId,{add:false,edit:false,del:false,search:false,refresh:false});
// add custom button to export the data to excel
resultsGrid.jqGrid('navButtonAdd',gridPagerId,{
caption:"Export",
onClickButton : function () {
resultsGrid.jqGrid('excelExport',{"url":csvUrl});
}
});
}; //end drawResultGrid function
//get grid config...
$.ajax({
type: "GET",
url: url,
data: "",
dataType: "json",
success: function(response)
{
if (response.result == "0")
{
logMessage("Drawing results grid...");
drawSearchResultsGrid(response.colNames,response.colModel,response.data);
resizeGrid();
logMessage("Results grid drawing done.");
}
else
{
logMessage("Error : " + response.message);
alert(response.message);
}
},
error: function(x, e)
{
alert(x.readyState + " "+ x.status +" "+ e.msg);
}
});
Here is my dynamic colModel looks like:
{
"result":"0",
"message":"",
"data":{
"records":18,
"total":1,
"page":"1",
"rows":[ ]
},
"colNames":[
"IP Address/Cidr",
"Name",
"IP Decimal",
"Cidr"
],
"colModel":[
{
"name":"adressCidr",
"width":50,
"sortable":true,
"hidden":false,
"sorttype":"function (cellValue,rowObject) { console.log('sorting by ['+rowObject.ipDecimal+']'); return parseInt(rowObject.ipDecimal,10);}"
},
{
"name":"name",
"width":50,
"sortable":true,
"hidden":false
},
{
"name":"ipDecimal",
"width":50,
"sortable":true,
"hidden":false,
"sorttype":"int"
},
{
"name":"cidr",
"width":0,
"sortable":false,
"hidden":true
}
]
}
ipDecimal is a hidden column but I am displaying it for testing purpose. Requirement is first column 'addressCidr' is a string column but i want to sort it using hidden ipDecimal column. The function neither does show console.log message nor does any sorting properly. However, If i sort by ipDecimal with sorttype as 'int' by clicking on its header, it works fine. Only thing i can think of is the double quote around the sorttype function itself. Please let me know if you see any other issue here, or what is the best way to solve this case. Here is snippet where I build json function:
private JsonObjectBuilder createColumn(JsonBuilderFactory factory,
String name,int width,boolean sortable,boolean hidden,boolean sorttype)
{
JsonObjectBuilder column =this.createColumn(factory, name, width, sortable, hidden);
StringBuilder fnBuilder = new StringBuilder("");
//this is not generic but can easily be made one :(
fnBuilder.append("function (cellValue,rowObject) {");
fnBuilder.append(" console.log('sorting by ['+rowObject.ipDecimal+']');");
fnBuilder.append(" return parseInt(rowObject.ipDecimal,10);");
fnBuilder.append("}");
column.add("sorttype", fnBuilder.toString()); // this works, not sure why above function does not work :(
return column;
}
private JsonObjectBuilder createColumn(JsonBuilderFactory factory,
String name,int width,boolean sortable,boolean hidden)
{
JsonObjectBuilder column;
column = factory.createObjectBuilder();
column.add("name", name);
column.add("width", width);
column.add("sortable", sortable);
column.add("hidden", hidden);
return column;
}
Data I used for testing is:
IpAddressCidr ipDecimal
5.1.0.0/24--83951616
5.1.1.0/24--83951872
5.1.2.0/24--83952128
5.1.3.0/24--83952384
5.1.4.0/24--83952640
5.3.0.0/24--84082688
5.9.2.0/24--84476416
6.0.0.0/24--100663296
6.0.1.0/24--100663552
6.0.2.0/24--100663808
6.0.3.0/24--100664064
6.0.4.0/24--100664320
6.0.5.0/24--100664576
7.1.0.0/24--117506048
7.1.1.0/24--117506304
7.1.2.0/24--117506560
7.1.3.0/24--117506816
198.186.198.0/24--3334129152
But here is that I see
Ip 198.186.198.0 should have appeared at the top as it has highest ipDecimal, but it gets pushed to the bottom.
To add more test information. If I remove enclosed double quotes, sort works fine, but not with it.
Following works:
{ name: "adressCidr", width:50, sortable: true,
sorttype: function (cellValue,rowObject) { console.log('sorting by ['+rowObject.ipDecimal+']');return parseInt(rowObject.ipDecimal,10);}},
Following does not:
{ name: "adressCidr", width:50, sortable: true,
sorttype: "function (cellValue,rowObject) { console.log('sorting by ['+rowObject.ipDecimal+']');return parseInt(rowObject.ipDecimal,10);}"},
The reason of your problem is the usage of sorttype which you defines as string instead of function:
{
"name":"adressCidr",
"width":50,
"sortable":true,
"hidden":false,
"sorttype":"function (cellValue,rowObject) { console.log('sorting by ['+rowObject.ipDecimal+']'); return parseInt(rowObject.ipDecimal,10);}"
}
You use jqGrid 4.7 which contains new feature which I suggested (see here). So you can include the code like
$.extend($.jgrid, {
cmTemplate: {
myIpAddress: {
sorttype: function (cellValue, rowObject) {
console.log('sorting by [' + rowObject.ipDecimal + ']');
return parseInt(rowObject.ipDecimal, 10);
},
width: 50
}
}
});
Now you can change the data returned from the server to
{
"name":"adressCidr",
"sortable":true,
"hidden":false,
"template":"myIpAddress"
}

Categories

Resources