Microsoft Most Valuable Professional

Chris Pietschmann

An MVP From Wisconsin



JavaScript: Loop through all elements in a form

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.

[code:html]
<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>
[/code]

Currently rated 3.6 by 14 people

  • Currently 3.571427/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Categories: General
Posted by crpietschmann on Thursday, June 01, 2006 9:02 AM
Permalink | Comments (4) | Post RSSRSS comment feed

Related posts

Comments

po[op[

Friday, June 30, 2006 10:20 AM

po[op[

p'l;l

Edison

Saturday, September 09, 2006 1:02 AM

Edison

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

Sunday, December 17, 2006 5:01 PM

BB

I agree with Edison, really nice! Thanks for sharing

George

Tuesday, March 27, 2007 5:32 AM

George

This code is gold. It's exactly what I was looking for! Thank you so much.

Comments are closed

About the author

I'm Chris Pietschmann, go to the About Me page to learn more about me.

Search

Sponsors

Web.Maps.VE - ASP.NET AJAX Virtual Earth Mapping Server Control

Recent comments

Disclaimer


This work is licensed under a Creative Commons Attribution 3.0 United States License, unless explicitly stated otherwise within the posted content.
© Copyright 2004 - 2008 Chris Pietschmann