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

Field 1:
Field 2:
Field 3:
Field 4:
Field 5:
Field 6:
Field 7:
Field 8:
Field 9:
Field 10:

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; };