Page 1 of 1

Javascript Arrays in DOM element

Posted: Thu Feb 07, 2008 1:45 pm
by GuitarheadCA
Hi,
I'd like to use an array to move through specific DOM elements to check form values on submit. Logically, I think it would look like this:

Code: Select all

 
<script language="javascript">
function checkform( form ) {
 
 //name,email,address all have values in the passed object...
 //ie, form.name.value contains the correct string
 
 var required_fields = Array('name','email','address');
 
 for (i=0; i<required_fields.length; i++) { // loop goes from 0-2
  if( form.required_fields[i].value == "" ) {  //<--error happening here
   alert('Please enter a valid ' + form.required_fields[i].value);
   return false;
  }
 }  
 return true; 
}
</script>
 
When I run this, it ignores the [] in the for loop, and throws an error that 'form.required_fields' is not a valid object. Any ideas?
Thanks.

Re: Javascript Arrays in DOM element

Posted: Thu Feb 07, 2008 2:25 pm
by VladSun
[js] form.elements[required_fields].... [/js]

Re: Javascript Arrays in DOM element

Posted: Thu Feb 07, 2008 5:40 pm
by GuitarheadCA
That did it! Thanks, I figured there was an easy way.