Accessing Form Data

Contact Us or call 1-877-932-8228
Accessing Form Data

Accessing Form Data

All forms on a web page are stored in the document.forms[] array. As we learned, JavaScript arrays having a starting index of 0, therefore the first form on a page is document.forms[0], the second form is document.forms[1], and so on. However, it is usually easier to give the forms names (with the name attribute) and refer to them that way. For example, a form named LoginForm can be referenced as document.LoginForm. The major advantage of naming forms is that the forms can be repositioned on the page without affecting the JavaScript.

Like with other elements, you can also give your forms ids and reference them with document.getElementById().

Elements within a form are properties of that form and can be referenced as follows:



Text fields and passwords have a value property that holds the text value of the field. The following example shows how JavaScript can access user-entered text:

Code Sample:

<meta charset="UTF-8">
<title>Form Fields</title>
<script type="text/javascript">
	function changeBg(){
		var userName = document.forms[0].userName.value;
		var bgColor = document.colorForm.color.value;

		document.bgColor = bgColor;
		alert(userName + ", the background color is " + bgColor + ".");
<h1>Change Background Color</h1>
<form name="colorForm">
	Your Name: <input type="text" name="userName"><br>
	Background Color: <input type="text" name="color"><br>
	<input type="button" value="Change Background" onclick="changeBg();">

Some things to notice:

  1. When the user clicks on the "Change Background" button, the changeBg() function is called.
  2. The values entered into the userName and color fields are stored in variables (userName and bgColor).
  3. This form can be referenced as forms[0] or colorForm. The userName field is referenced as document.forms[0].userName.value and the color field is referenced as document.colorForm.color.value.