I am trying to write some validation script using javascript and prototype.
What I want to do is iterate over all the elements of the form and check each answer. My code works, BUT the array of DOM elements is unsorted. I would like to sort the elements by their id.
Here is my code that works fine if I comment on 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 wonder if the problem might be that some elements have no names. Does anyone have another easier way to sort an array of DOM elements through their .name?
source
share