Jump to content

How to select all elements of a form?


mostafatalebi

Recommended Posts

This is my code

 

<body>

<form action="" method="post" name="exm">
<input type="text" name="name">
<input type="text" name="x">
<input type="text" name="y">
<input type="text" name="z">
<input type="submit" name="submit" />
<script type='text/javascript' >

function formValue ()
   {
           document.forms['exm'].elements.value= "AAA";
   }
formValue;    
</script>
</form>
</body>

Your current method treats the elements property of the form object as an object with a property of value

 

form = {
  element: {
     value: "Somethnig"
  }
}.

 

When in fact its along the lines of

 

form = { 
  elements : array(
      0 => Button,  1 => Text, 2 => Checkbox
  )
}

 

There are further technicalities that going into detail will serve no purpose as you wont understand.

 

So you need to cycle through the array:

 

for(i = 0; i <= document.forms["Myform"].elements.length; i++) {
  // Code omitted
}

So you need to cycle through the array:

 

for(i = 0; i <= document.forms["Myform"].elements.length; i++) {
  // Code omitted
}

 

Wouldn't that calculate the form length each time? I think it might be a little better to do something like ..

for (var i = 0, n = document.forms["Myform"].elements.length; i <= n; i++)

.length is of type Number. I'm not sure which method is called by default when using .length but either way the affect will be negligible so either method would suffice. That said I would define n outside the loop for clarity and readability purposes.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.