i have arrays of input controls and want to check on submit that they should not be empty
Here's an example function:
function valid( array ) {
if( typeof array != 'object' || array.length < 1 ) return false; // some basic error checking
var errors = [];
var alen = array.length;
for( var a = 0; a < alen; a++ ) {
if( array[ a ].value.length < 1 ) errors.push( array[ a ] );
}
if( errors.length >= 1 ) return errors;
return true;
}
Usage:
function submitForm() {
var inputs = document.getElementsByTagName( 'input' );
var errors = valid( inputs );
if( errors ) {
var elen = errors.length;
for( var e = 0; e < elen; e++ ) {
errors[ e ].className = "error";
}
event.preventDefault();
return false;
}
}
var form = document.getElementById( 'myForm' ).onsubmit = submitForm;
If you were using a framework, this would be even easier.
errors[e].className = "error";, also I would recommend to use a normal for or while loop instead the for...in statement for iterating the arrays...for...in s to for s, but i'm not sure why you prefer that over the for...in.for...in statement should be used to iterate over object properties, is not recommended for arrays because it goes up in the prototype chain, and if something extended the native Array.prototype object (some libraries like MooTools do it), those properties will be also iterated, another point is that the order of iteration is not guaranteed, so the elements may not visited in its numerical order. More info: developer.mozilla.org/En/Core_JavaScript_1.5_Reference/…