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.

<html>
<head>
<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;
    }
</script>
</head>
<body>
    <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();" /> 
    </form>
    <hr />
    <div id="lblValues"></div>
</body>
</html>

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

JavaScript, JavaScript, JavaScript, JavaScript ,

Comments

po[op[
po[op[
7/3/2006 12:20:00 PM #
p'l;l
Edison
Edison
9/12/2006 3:02:00 AM #
The code snippet is exactly what I am looking for. This is a very good example of how it can help people to learn Javascript by example. Keeping it simple is the key. Thankyou very much for this.
BB
BB
12/20/2006 7:01:00 PM #
I agree with Edison, really nice! Thanks for sharing
3/30/2007 7:32:00 AM #
This code is gold.  It's exactly what I was looking for!  Thank you so much.
11/7/2009 12:23:17 AM #
Pingback from blog.wu-boy.com

[網站] 好站連結 (六) | 小惡魔 - 電腦技術 - 生活日記 - 美食介紹 - AppleBOY
5/21/2010 8:39:27 PM #
Pingback from 149.eumreborn.com

Sl320 Part Headlight Assembly 1997 Mercedes, Sl320 Used Mercedes Benz Auto Parts