Array and sorting demo II
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.
Data to sort
The JavaScript code:
function numericCompare(a, b) { return a - b; }
// sorts numerically if all elements are numbers
// otherwise it sorts alphabetically
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(numericCompare);
else nums.sort();
for (var i=0; i<nums.length; i++) fields[i].value=nums[i];
return false;
}
window.onload = function() {
document.getElementById('sortform').onsubmit = sortme;
};