0

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

0

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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, 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.
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: developer.mozilla.org/En/Core_JavaScript_1.5_Reference/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.