X
HOME HTML CSS JAVASCRIPT SQL PHP JQUERY XML ASP.NET MORE...
REFERENCES | EXAMPLES | FORUM | ABOUT

Form elements Collection

Form Object Reference Form Object

Example

Return the value of each element in a form:

var x = document.getElementById("myForm");
var txt = "";
for (var i=0; i<x.length; i++)
  {
  txt = txt + x.elements[i].value + "<br>";
  }
document.getElementById("demo").innerHTML=txt;

The result of txt will be:

Donald
Duck
Submit

Try it yourself »


Definition and Usage

The elements collection returns a collection of all elements in a form.

Note: The elements in the collection are sorted as they appear in the source code.


Browser Support

Internet Explorer Firefox Opera Google Chrome Safari

The elements collection is supported in all major browsers.


Syntax

formObject.elements

Properties

Property Description
length Returns the number of form elements in the collection

Methods

Method Description
[name_or_index] A string or integer that specifies the element to retrieve (index starts at 0)
item(name_or_index) Returns the element from the collection with the specified index/name/id
namedItem(name_or_id) Returns the element from the collection with the specified name (name or id attribute)


More Examples

Example

Show the number of elements in a form:

var x = document.getElementById("myForm").elements.length;
document.getElementById("demo").innerHTML=x;

The result of x will be:

3

Try it yourself »

Example

[name_or_index]

Return the value of the first element (index 0) in a form:

var x = document.getElementById("myForm").elements[0].value;
document.getElementById("demo").innerHTML=x;

The result of x will be:

Donald

Try it yourself »

Example

item(name_or_index)

Return the value of the first element (index 0) in a form:

var x = document.getElementById("myForm").elements.item(0).value;
document.getElementById("demo").innerHTML=x;

The result of x will be:

Donald

Try it yourself »

Example

namedItem(name_or_id)

Return the value of the element with name="fname" in a form:

var x = document.getElementById("myForm").elements.namedItem("fname").value;
document.getElementById("demo").innerHTML=x;

The result of x will be:

Donald

Try it yourself »


Form Object Reference Form Object

Your suggestion:

Close [X]

Thank You For Helping Us!

Your message has been sent to W3Schools.

Close [X]
Search w3schools.com:

WEB BUILDING

Download XML Editor FREE Website BUILDER Free HTML5 Templates FREE Website Templates Free HTML Templates

SHARE THIS PAGE

facebook