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 Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s