Numeric Column Sorting in jqGrid

When we set the Sort Column and Sort Direction in a jqGrid, it considers the column as text by default. Even when you are sorting with numeric columns, it sorts as text.
For example – The rows on the left side will be sorted as right

1                                                      1
2                                                     100
3                                                     101
100                                                 102
101                       =>                      2
102                                                 201
201                                                 202
202                                                203
203                                                3

This happens as jqGrid considers them as text columns. For solving this problem, we can use Custom Sorting. In your colModel, specify the sorttype and use this function.

colModel: [
  { name:'rowId', index:'rowId',
    sorttype: function(cell,rowObject) {
        if (typeof cell === "string" && /^test(\d)+$/i.test(cell)) {
             return parseInt(cell.substring(4),10);
        } else {
             return cell;
        }
    }
  }
]

Leave a Comment

Your email address will not be published. Required fields are marked *