Array and sorting demo III
Note: This sort will sort numerically if all of the data is
numeric. If the data is not all numbers, then the sort will sort
alphabetically. In this case the sort will be done in descending
order and an anonymous compare function will be provided for
the reverse numeric sort.
Data to sort
The JavaScript code:
// sorts numerically if all elements are numbers
// otherwise it sorts alphabetically; sort is
// done in descending order
function sortme() {
var numsort = true;
var fields = document.getElementsByTagName("INPUT");
var nums = new Array();
for (var i=0; i<fields.length; i++) {
var x = parseFloat(fields[i].value);
if (isNaN(x)) numsort = false;
nums.push(fields[i].value);
}
if (numsort) nums.sort(function(a,b) { return b - a; });
else nums.sort().reverse();
for (var i=0; i<nums.length; i++) fields[i].value=nums[i];
return false;
}
window.onload = function() {
document.getElementById('sortform').onsubmit = sortme;
};