volosoft / jtable

A JQuery plugin to create AJAX based CRUD tables.
http://www.jtable.org
1.1k stars 506 forks source link

optionsSorting not working for numeric values #2277

Open goldfoot opened 1 year ago

goldfoot commented 1 year ago

jTable: 2.5.0

I have a field with options like to:

{
    "title": "My field",
    "options": {
        "1": "Some Label",
        "5": "Some Label",
        "7": "Some Label",
        "8": "Some Label",
        "11": "Some Label",
        "13": "Some Label",
        "15": "Some Label",
        "16": "Some Label",
        "96": "Some Label",
        "97": "Some Label",
        "98": "Some Label",
        "99": "Some Label",
        "100": "Some Label",
        "101": "Some Label",
        "102": "Some Label",
        "103": "Some Label"
    },
    "optionsSorting": "value-desc",
}

The object is parsed from JSON, so it is not possible for me to use numeric keys directly.

I expected that the options would be sorted from highest numeric values to lowest numeric values in the dropdown of the create.and edit forms. However, this is not the case. The options get sorted by value (so 1, 5, 7, etc.), but the values are treated as string values. Instead of a numerically descending order, the options are sorted in the lexicographic order, resulting in: 99, 98, 97, 96, 16, 15, 13, 103, 102, ...

After some research of the jTable source code, i found that the type check of the value done in https://github.com/volosoft/jtable/blob/master/jquery.jtable.js#L955 is not respecting numeric values in quotes as such. So I changed

if ($.type(dataSelector(options[0])) == 'string') {
    // lexicographic sorting
} else {
   // numeric sorting
}

to

if (!$.isNumeric(dataSelector(options[0]))) {
    // lexicographic sorting
} else {
   // numeric sorting
}

This seems to work, even if the keys of the object are numeric values in quotes.