Currently, I am working on writing a validation script using JavaScript and prototype.
The main idea behind this task is to iterate through all the elements of a form and validate each answer. While my code is functional, there is an issue with the array of DOM elements being unsorted. Ideally, I would like to sort the elements based on their ID.
Below is the snippet of my code. It works perfectly unless I comment out elem.sort(zelementsort);
function zelementsort(a,b) {
if (a.name > b.name)
return -1;
else if (b.name > a.name)
return 1;
else
return 0;
}
var elem = document.getElementById('myform').elements;
elem.sort(zelementsort);
for(var i = 0; i < elem.length; i++)
{
alert("Name = " + elem[i].name);
}
I suspect that some elements might not have names, causing potential issues. Does anyone know of a simpler way to sort an array of DOM elements by their .name attribute?