Loop/Iterate through all Elements in a form with javascript


Sometimes you really want to iterate through all elements of a form, especially

if you want to debug and you want to know about every element in your form.

Also if you want to perform same function similar elements, this comes in handy.

For example, if you want to check/uncheck all the checkboxes in your form. To see this

example click here

for(i=0; i<document.fornName.elements.length; i++){
alert("The field name is: " + document.fornName.elements[i].name +
    " and it’s value is: " + document.fornName.elements[i].value );

6 Responses to “Loop/Iterate through all Elements in a form with javascript”

  1. 1 geoto

    Nice scripts

  2. Thanks! Exactly what I was looking for.

  3. 3 beginnerScripter

    I have this same javascript on an asp page which includes asp labels. The elements collection does not seem to include the labels: the script is showing the buttons and the viewstate only. Am I doing something wrong or is this the expected behavior?

  4. 4 Sonny Davao


    i think labels are not considered form elements that can have values.

    what i do is just use textboxes but display it as a label through formatting (no borders, transparent backgrounds)

    when its a textbox, you can loop through it in code behind or javascript

  5. The .elements is contains the LENGTH property of the form, so you should use a condition before you run any function based on tagName. fe. in a for cycle: var element = form.elements[i]; if(element.tagName){ function run }
    if you leave the condition, you will also loop on the LENGTH of the form, what could make some error, because the element will equal to 84 if you have 84 form element… i hope you understand me 🙂

  6. by the way “beginnerScripter” , if you want to get the label fot an element, you can do it easily. First of all, you should get the element’s name or id, what you used. Look my example code.

    when you loop over the elements, you can get the id of the element, by “var id= element.getAttribute(‘id’);” , and after that, with the “getElementByTagName(‘label’)” you can get the labels array, what should contains the label for your input, now you just have to check, as what label is contains your ID, what is a simple for cycle, and if….
    best regards

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: