Javascript-HTML - how to iterate through all the forms on a page?
Asked Answered
C

3

11

How can I iterate through all forms in a document using javascript?

Concerted answered 27/1, 2010 at 11:17 Comment(0)
P
12

The code below will go through an html document, get all forms and do a pop-up alert of the names of each form.

var formsCollection = document.getElementsByTagName("form");
for(var i=0;i<formsCollection.length;i++)
{
   alert(formsCollection[i].name);
}

This is just a start to see if you are getting the reult you require. Thereafter, remove the alert and continue to do what you need to.

Piotr answered 27/1, 2010 at 11:32 Comment(2)
Obviously because your answer is less elegant then pulse .. I didn't give you vote down btwMama
I didn't vote, but note that the "name" attribute has little use on a form, so you'll seldom see it. One would find the uniqueness and addressability of "id" to be more useful, but neither affect the form's functionality.Commissar
B
16

You can use

document.forms collection

See forms Collection

Bumblebee answered 27/1, 2010 at 11:19 Comment(2)
this should be best answer :)Zoan
Much simpler than trying to grab the element by the Tag, ID, or Name as they could be different.Sauna
P
12

The code below will go through an html document, get all forms and do a pop-up alert of the names of each form.

var formsCollection = document.getElementsByTagName("form");
for(var i=0;i<formsCollection.length;i++)
{
   alert(formsCollection[i].name);
}

This is just a start to see if you are getting the reult you require. Thereafter, remove the alert and continue to do what you need to.

Piotr answered 27/1, 2010 at 11:32 Comment(2)
Obviously because your answer is less elegant then pulse .. I didn't give you vote down btwMama
I didn't vote, but note that the "name" attribute has little use on a form, so you'll seldom see it. One would find the uniqueness and addressability of "id" to be more useful, but neither affect the form's functionality.Commissar
F
2

Here's an example using the document.forms instead of getElementsByTagName().

As with the getElementsByTagName() example this goes through all the forms and does a popup alert with the action (instead of name, as it is more likely to be set).

var formsCollection;
var r;

formsCollection=document.forms;

for(r=0;r<formsCollection.length;r++)
{
    alert(formsCollection[r].action);
}

This can be condensed down and of course the popup changed to something useful but I have tried to keep it simple.

And for reference here are some links to more info:

Fertile answered 30/4, 2014 at 14:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.