tags:

views:

56

answers:

2

i have arrays of input controls and want to check on submit that they should not be empty

+3  A: 

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.

Jacob Relkin
A small typo, when setting the error class, should be `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...
CMS
@CMS, corrected all the errors, and I changed the `for...in` s to `for` s, but i'm not sure why you prefer that over the `for...in`.
Jacob Relkin
@Jacob, the `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: https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Statements/For...in#section_4
CMS
A: 

Can you share the HTML markup that your working with?

alvincrespo
You could have asked this in a comment to the question - that's what comments are there for.
Amarghosh
Whoever upvoted this, I am puzzled as to why, this is not an answer!
Jacob Relkin
I would have left a comment, but I need 50 reputation points :(
alvincrespo