DataTables sorting on non-numeric column with input field - sorting

I am following this DataTables example to add sorting on columns with an input field: http://datatables.net/examples/plug-ins/dom_sort.html
In my code below, the second targeted column (6), is a numeric field, and sorts fine, however the first column (5), a text column, doesn't sort at all. Using Chrome developer tools I can see it stepping into the function, but no sorting takes place. Both columns are input fields. I am using the latest DataTables version, 1.10.7.
$.fn.dataTable.ext.order['dom-text'] = function ( settings, col )
{
return this.api().column( col, {order:'index'} ).nodes().map( function ( td, i ) {
return $('input', td).val();
} );
}
var table = $("#example").DataTable({
"scrollY": "500px",
"scrollX": "675px",
"scrollCollapse": true,
"paging": false,
"order": [],
"deferRender": true,
"orderClasses": false,
"columnDefs": [
{ "orderDataType": "dom-text", "targets": [5,6] }
]
});

SOLUTION
As in the Live DOM Ordering example, you need to use dom-text for sorting <input> elements containing text and dom-text-numeric for sorting <input> elements containing numbers.
/* Create an array with the values of all the input boxes in a column */
$.fn.dataTable.ext.order['dom-text'] = function ( settings, col )
{
return this.api().column( col, {order:'index'} ).nodes().map( function ( td, i ) {
return $('input', td).val();
} );
}
/* Create an array with the values of all the input boxes in a column, parsed as numbers */
$.fn.dataTable.ext.order['dom-text-numeric'] = function ( settings, col )
{
return this.api().column( col, {order:'index'} ).nodes().map( function ( td, i ) {
return $('input', td).val() * 1;
} );
}
$(document).ready(function (){
$('#example').dataTable( {
/* ... other options ... */
"columnDefs": [
{ "targets": 1, "orderDataType": "dom-text-numeric" },
{ "targets": 2, "orderDataType": "dom-text", "type": "string" }
]
} );
});
DEMO
See this jsFiddle for code and demonstration.

Related

How to access column name dynamically in Kendo Grid template

I need to access the column name dynamically in Kendo Grid template.
Code:
$("#grid").kendoGrid({
dataSource: [
{ Quantity: 2 , Amount: 650},
{ Quantity: 0, Amount: 0 },
{ Quantity: 1, Amount: 500 },
{ Quantity: 4, Amount: 1047 }
],
sortable: true,
columns: [
{
field: "Quantity",
template: function (dataItem) {
if (dataItem.Quantity == '0') {
return "--";
} else {
return dataItem.Quantity;
}
}
},
{
field: "Amount",
template: function (dataItem) {
if (dataItem.Amount == '0') {
return "--";
} else {
return dataItem.Amount;
}
}
}
]
});
Here inside the "columns -> template", I need to access the column thru variable instead of hardcoding it. How can I do that? Because in real life I will be having dynamic columns populated into dataSource and I will construct the columns array inside the for loop. Please help.
Please access this JSBIN: http://jsbin.com/egoneWe/1/edit
From what I understand, you build the columns array using something like:
var Definition = [
{ field: "Quantity" },
{ field: "Amount" }
];
var columns = [];
$.each(Definition, function (idx, item) {
columns.push({
field : item.field,
template: function (dataItem) {
...;
}
})
});
$("#grid").kendoGrid({
dataSource: data,
sortable : true,
columns : columns
});
Right? And the problem is that you want to use the same template function for several (all) columns instead of having to rewrite many.
If so, what you can do is:
var Definition = [
{ field: "Quantity" },
{ field: "Amount" }
];
var columns = [];
$.each(Definition, function (idx, item) {
columns.push({
field : item.field,
template: function (dataItem) {
return commonTemplateFunction(dataItem, item.field);
}
})
});
What I use in the columns array (columns definition for the Grid) is a function that receives two arguments: the dataItem for the row and the field's name being edited.
Then, I define the template function as:
function commonTemplateFunction(dataItem, field) {
if (dataItem[field] == '0') {
return "--";
} else {
return dataItem[field];
}
}
And your modified code is here : http://jsbin.com/egoneWe/3/edit
So, despite I cannot guess the column name, I can do the trick using the columns initiator.

Filter a value in dropdown list with value in a column

I have a kendo grid with custom toolbar template, my drop down list have only one float value
Now I want filter grid by that value and a column ( not ID) and get greater than or less than. How can I do ( I work with kendo-asp.net-mvc )
If I've understood correctly, you want to filter your grid based on a value from a dropdown.
You can add a handler to your search button click event that fills the grid filters and then filters the grid:
$( function () {
$( "#btnSearch" ).click( function ( e ) {
e.preventDefault();
$filter = new Array();
$dropdownValue = $( "#YOUR_DROPDOWN_ID" ).val();
if ( $dropdownValue ) {
$filter.push( { field: "GRID_FIELD", operator: "gt", value: $dropdownValue } );
$filter.push( { field: "GRID_FIELD", operator: "lt", value: $dropdownValue } );
}
var grid = $( "#Grid" ).data( "kendoGrid" );
grid.dataSource.filter( $filter );
} );
} );

is there a way to auto adjust widths in ng-grid?

I'm having trouble with widths of my columns. I don't know what width they will be beforehand, nor do I want to specify each column's width. Is there an attribute that I can use that auto adjusts all the column widths based on the content (including the column header)?
Woot! I came up with a pretty cool answer! Setting the width to "auto" was really not working for me. Maybe it is because I'm using an ng-view? Not sure. So I created 2 new functions you can put in your controller.js. Using them like this will give you computed column widths! Read the code comments; there are some caveats.
Example usage, controllers.js:
var colDefs = makeColDefs(rows[0]);
colDefs = autoColWidth(colDefs, rows[0]);
$scope.phones = rows;
$scope.gridOptions = {
data : 'phones',
showFilter : true,
enableColumnResize : true,
columnDefs : colDefs
};
The code, controllers.js:
/**
* Create a colDefs array for use with ng-grid "gridOptions". Pass in an object
* which is a single row of your data!
*/
function makeColDefs(row) {
var colDefs = [];
for ( var colName in row) {
colDefs.push({
'field' : colName
});
}
return colDefs;
}
/**
* Return a colDefs array for use with ng-grid "gridOptions". Work around for
* "auto" width not working in ng-grid. colDefs array will have percentage
* widths added. Pass in an object which is a single row of your data! This
* function does not do typeface width! Use a fixed width font. Pass in an
* existing colDefs array and widths will be added!
*/
function autoColWidth(colDefs, row) {
var totalChars = 0;
for ( var colName in row) {
// Convert numbers to strings here so length will work.
totalChars += (new String(row[colName])).length;
}
colDefs.forEach(function(colDef) {
var numChars = (new String(row[colDef.field])).length;
colDef.width = (numChars / totalChars * 100) + "%";
});
return colDefs;
}
Jasmine test, controllerSpec.js:
'use strict';
var ROW = {
'col1' : 'a',
'col2' : 2,
'col3' : 'cat'
};
var COLUMN_DEF = [ {
field : 'col1'
}, {
field : 'col2'
}, {
field : 'col3'
} ];
var COLUMN_DEF2 = [ {
field : 'col1',
width : '20%'
}, {
field : 'col2',
width : '20%'
}, {
field : 'col3',
width : '60%'
} ];
/* jasmine specs for controllers go here */
describe('controllers', function() {
beforeEach(module('myApp.controllers'));
it('should make an ng-grid columnDef array from a row of data.',
function() {
expect(makeColDefs(ROW)).toEqual(COLUMN_DEF);
});
it('should return an ng-grid columnDef array with widths!', function() {
var colDefs = makeColDefs(ROW);
expect(autoColWidth(colDefs, ROW)).toEqual(COLUMN_DEF2);
});
});
Use ui-grid, is must better: http://ui-grid.info/docs/#/tutorial/204_column_resizing
but https://github.com/angular-ui/ng-grid/wiki/Configuration-Options
This works:
$scope.gridOptions = {
init: function (gridCtrl, gridScope) {
gridScope.$on('ngGridEventData', function () {
$timeout(function () {
angular.forEach(gridScope.columns, function (col) {
gridCtrl.resizeOnData(col);
});
});
});
},
data: 'scopeDataField',
columnDefs: [
{
field: 'property1',
displayName: 'property1title',
width: '100px' // a random fixed size, doesn't work without this
},
{
field: 'property2',
displayName: 'property2title',
width: '100px'
}
],
enableColumnResize : true
};
See answer at https://stackoverflow.com/a/32605748/1688306
Column width calculated by column name or datum, whichever is longer.
Yes! In your columndefs you can set the width to auto and this will automatically size the columns based on the width of the data and/or header.
Reference: Defining Columns
I am using ui-grid. The following code is working for me. You can try this.
First you need to add a module dependency 'ui.grid.autoResize' in your main module.
Then add css class something like this
.grid {
width : 400px !important;
max-width : 400px !important;
height : 600px !important;
}
And finally add the ui-grid directive in your html file like this. Keep in mind don't forgot to add the 'ui-grid-auto-resize' in your grid directive.
<div id="grid1" ui-grid="gridOptions" class="grid" ui-grid-auto-resize></div>

jqGrid: is it possible to selectively make cells editable?

how can I make one single cell editable out of a not editable column?
my javaScript looks like this:
$( '#grid' ).jqGrid({
// ...
cellEdit : true,
colModel : [
{ name : "id", index : "id", editable : false },
{ name : "wbs", index : "wbs", editable : false },
{ name : "value", index : "value", editable : false }
],
loadComplete : function(data) {
// ... foreach ( cell in data.rows.columns ) ...
if ( cell.shouldBeEditable ) {
jQuery('#grid').setCell(cell.row, cell.col, '', 'green', { editable : true });
}
}
// ...
}
so, after globally setting columns as not editable, I try to set them as editable locally, based on some criteria (to identify them more easily I also paint them green).
Alas, it's not working: cells become green, but when I try to click them they do not become editable.
Inspecting the selected cell with firebug reveals the edit-cell class to be correctly applied.
As a last note, it's working if I set columns as editable in the first instance.
I suggest you do it in reverse. Make the column editable, but disable the cells that you do not want to be editable. This is a function I wrote to disable cells:
// cellName is the name defined in your colModel
function disableGridCell(cellName) {
var cell = $('[name="' + cellName + '"]');
cell.css('display', 'none');
var div = $("<div>")
.css('width', '100%')
.css('height', '100%')
.css('border', '1px solid #000')
.css('background-color', '#CCC')
.text('xxxxxxxxxxxx');
cell.parent().append(div);
}
I call disableGridCell inside of my onEditFunc of my grid's editRow function:
$('#grid').jqGrid('editRow', id, keys, onEditFunc);
function onEditFunc(id) {
if (condition to disable cell) {
disableGridCell('CellName');
}
}
I found a nice workaround to the problem (thanks to Walter for getting me on the right track).
Instead of locking all the cells and selectively unlocking them in a declarative manner (which may lead to long load times), I'm declaring all the cells as editable.
Then I'm attaching a callback to afterEditCell option:
var $grid = $('#grid');
$grid.jqGrid({
// ...
afterEditCell : function(rowid, cellname, value, iRow, iCol) {
if ( shouldNotBeEditable(iRow, iCol) ) {
$grid.setCell(rowid, cellname, '', 'not-editable-cell');
$grid.restoreCell(iRow, iCol);
}
},
// ...
});
This way the cell is immediately reset to its previous value and I ensure that the callback gets called only once per not-to-be-edited cell, since the cell is made into a not-editable-cell after the first call.
colModel:[
{name:'description',index:'description', width:4, sortable: false, editable: true},
{name:'qty',index:'qty', width:1,sortable: false, editable: true},
{name:'cost',index:'cost', width:1, editable: true, sortable: false},
{name:'totalCost',index:'totalCost', width:1, sortable: false}
onCellSelect: function(rowid, iCol, cellcontent, e) {
//here it will allow editing of either qty or cost col for that rowid
//only if both cols have a numeric value already
if(iCol===1 || iCol===2) {
var rowdata = $("#projectTable").getRowData(rowid);
var itemCost = parseInt(rowdata['cost']);
var qty = parseInt(rowdata['qty']);
if(!$.isNumeric(itemCost) || !$.isNumeric(qty)) {
$("#projectTable").jqGrid('setColProp','qty',{editable: false});
$("#projectTable").jqGrid('setColProp','cost',{editable: false});
} else {
$("#projectTable").jqGrid('setColProp','qty',{editable: true});
$("#projectTable").jqGrid('setColProp','cost',{editable: true});
}
}
},

jqgrid: several questions - matrix display

I have data of matrix stored in table as below tables:
MatrixDimensions - MatrixId, NoOfRows, NoOfCol
MatrixValues - MatrixId, RowNo, ColNo, Value
How can I make jqGrid to take no. of rows & columns dynamically
and also display the serialized data in matrix? Is there a direct way or will I have to implement for loops to upload the data in matrix?
Can I display rows as columns and columns as rows (so having column headers vertically aligned)?
Can I enable only inline editing and disable form based editing?
I just wrote the answer to another question where I described how to create the grid with dynamic number of columns (number of rows is always dynamic in jqGrid). It seems to me this way you can display any matrix. In you case you can probably make the code simpler because you can use generic column names like "1", "2", etc. (or "Col. 1", "Col. 2", etc.) and so on.
I modified the code so that it uses array of arrays (matrix) instead of the array on objects with named properties. So jqGrid will looks like this:
or this:
depending on the input JSON data.
The full demo can be found here. The full JavaScript code of the demo you can find below:
var mygrid=jQuery("#list"),
cmTxtTemplate = {
width:40,
align:"center",
sortable:false,
hidden:true
}, currentTemplate = cmTxtTemplate, i,
cm = [], maxCol = 30, dummyColumnNamePrefix = "", //"Col. ",
clearShrinkToFit = function() {
// save the original value of shrinkToFit
var orgShrinkToFit = mygrid.jqGrid('getGridParam','shrinkToFit');
// set shrinkToFit:false to prevent shrinking
// the grid columns after its showing or hiding
mygrid.jqGrid('setGridParam',{shrinkToFit:false});
return orgShrinkToFit;
},
setGridWidthAndRestoreShrinkToFit = function(orgShrinkToFit,width) {
// restore the original value of shrinkToFit
mygrid.jqGrid('setGridParam',{shrinkToFit:orgShrinkToFit});
mygrid.jqGrid('setGridWidth',width);
},
dummyTestRegex = new RegExp(dummyColumnNamePrefix+"(\\d)+"),
counter = 1;
// Add dummy hidden columns. All the columns has the same template
for (i=0;i<maxCol;i++) {
cm.push({name:dummyColumnNamePrefix+(i+1),template:currentTemplate});
}
mygrid.jqGrid({
url:'Matrix1.json',
datatype: "json",
// colNames will be set based on the properties for JSON input
colModel:cm,
height:"auto",
rownumbers:true,
loadonce:true,
gridview: true,
rowNum: 1000,
sortname:"",
jsonReader: {
cell: "",
id: function (obj) {
return "id"+counter++;
},
page: function (obj) {
var rows = obj.rows, colModel = mygrid[0].p.colModel,
cmi, width = 0, iFirstDummy, cols, orgShrinkToFit,
showColNames = [], hideColNames = [];
if (typeof(rows) === "undefined" || !(rows.length>0)) {
// something wrong need return
return obj.page;
}
// find the index of the first dummy column
// in the colModel. If we use rownumbers:true,
// multiselect:true or subGrid:true additional
// columns will be inserted at the begining
// of the colModel
iFirstDummy = -1;
for(i=0;i<colModel.length;i++) {
cmi = colModel[i];
if (dummyTestRegex.test(cmi.name)) {
iFirstDummy = i;
break;
}
}
if (iFirstDummy === -1) {
// something wrong need return
return obj.page;
}
orgShrinkToFit = clearShrinkToFit();
// we get the first row of the JSON data
cols = rows[0].length;
// fill the list of unused columns
for(i=0;i<colModel.length;i++) {
cmi = colModel[i];
if (i<iFirstDummy+cols) {
cmi.width = currentTemplate.width;
showColNames.push(cmi.name);
} else {
hideColNames.push(cmi.name);
}
}
mygrid.jqGrid('showCol',showColNames);
mygrid.jqGrid('hideCol',hideColNames);
setGridWidthAndRestoreShrinkToFit(orgShrinkToFit,
cols*currentTemplate.width);
return obj.page;
}
}
});
$("#readJson1").click(function() {
mygrid.jqGrid('setGridParam',
{datatype:'json',page:1,url:'Matrix1.json'})
.trigger('reloadGrid');
});
$("#readJson2").click(function() {
mygrid.jqGrid('setGridParam',
{datatype:'json',page:1,url:'Matrix2.json'})
.trigger('reloadGrid');
});
The simplest way to transpose the matrix (reflect it over its main diagonal) is on the server. If you can't do this, you can create and fill the transposed matrix inside of page function (see my code above) and just replace the row part of the obj with the transposed matrix.

Resources