Reputation: 2553
I am using the ENUM sorting routine found at http://datatables.net/plug-ins/sorting. I would like to reuse that same function to sort another list outside of the DataTables plug-in (basically sorting a SELECT element on the same page as the DataTable). I want to avoid having to copy-and-paste (and maintain two sets of business rules) the features of the sort function.
For example, if this is the "plug-in" I'm using for DataTables:
jQuery.extend(jQuery.fn.dataTableExt.oSort, {
"status-enum-pre": function (a) {
switch (a) {
case "Assigned": return 1;
case "Contacted": return 2;
case "Meeting Set": return 3;
case "Closed": return 4;
default: return 5;
}
},
"status-enum-asc": function (a, b) {
return ((a < b) ? -1 : ((a > b) ? 1 : 0));
},
"status-enum-desc": function (a, b) {
return ((a < b) ? 1 : ((a > b) ? -1 : 0));
}
});
How can I re-use that function to sort the following select list?
<select>
<option value="Contacted">Contacted</option>
<option value="Assigned">Assigned</option>
<option value="Closed">Closed</option>
<option value="Meeting Set">Meeting Set</option>
</select>
Upvotes: 0
Views: 725
Reputation: 91329
Obtain the required sort function from the jQuery.fn.dataTableExt.oSort
property, and then pass it to Array#sort
, which receives a comparator function. For example, to sort a select
using status-enum-asc
, you'd need:
// Plugin sort functions
var sortFn = jQuery.fn.dataTableExt.oSort["status-enum-pre"];
var sortDirFn = jQuery.fn.dataTableExt.oSort["status-enum-desc"];
// Sort
var options = $("select option");
options.sort(function(a,b) {
return sortDirFn(sortFn(a.text), sortFn(b.text));
});
// Empty and append sorted options
$("select").empty().append(options);
DEMO.
Upvotes: 1