Javascript Arrays in DOM element

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
GuitarheadCA
Forum Newbie
Posts: 20
Joined: Fri Jul 13, 2007 12:59 am

Javascript Arrays in DOM element

Post 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.
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

Re: Javascript Arrays in DOM element

Post by VladSun »

[js] form.elements[required_fields].... [/js]
There are 10 types of people in this world, those who understand binary and those who don't
GuitarheadCA
Forum Newbie
Posts: 20
Joined: Fri Jul 13, 2007 12:59 am

Re: Javascript Arrays in DOM element

Post by GuitarheadCA »

That did it! Thanks, I figured there was an easy way.
Post Reply