JavaScript, jquery

JavaScript: Loop through all elements in a form

JavaScript: Loop through all elements in a form

1. June 2006

Since I’ve been doing alot of JavaScript programming lately, I figured I could start blogging some code snippets. Here is a JavaScript snippet that shows how to loop through all the elements in a form and retrieve their element type, name and values. I had to use this code to gather all form values so I could post them to the server using AJAX.

<script type="text/javascript">
    function DisplayFormValues()
        var str = '';
        var elem = document.getElementById('frmMain').elements;
        for(var i = 0; i < elem.length; i++)
            str += "<b>Type:</b>" + elem[i].type + "&nbsp&nbsp";
            str += "<b>Name:</b>" + elem[i].name + "&nbsp;&nbsp;";
            str += "<b>Value:</b><i>" + elem[i].value + "</i>&nbsp;&nbsp;";
            str += "<BR>";
        document.getElementById('lblValues').innerHTML = str;
    <form id="frmMain" name="frmMain">
        <input type="hidden" name="ElemHidden" value="some hidden text" />
        <input type="text" name="ElemText" value="some text" /><br />
        <textarea name="ElemTextArea">Some text area text</textarea><br />
        <br />
        <input type="button" value="Test" onclick="DisplayFormValues();" /> 
    <hr />
    <div id="lblValues"></div>

I revisited this code and tested it again to make sure it still works. I found that it works with the latest browser versions available today, in addition to older browsers, such as:

  • Internet Explorer 6, 7, 8
  • FireFox 3 & 4 Beta 4
  • Google Chrome

2 thoughts on “JavaScript: Loop through all elements in a form”

  1. Just started doing javascript at school. I was looking for something like this a few weeks ago but to no avail and gave up looking. It annoyed me I couldnt get it but it makes so much sense now I see it! Thanks. Brilliant…. 🙂

Leave a Reply

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

You are commenting using your 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 )

Google+ photo

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

Connecting to %s