Accessing Form Data

Welcome to our free JavaScript tutorial. This tutorial is based on Webucator's Introduction to JavaScript Training course.

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. 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 reference forms via their id attribute and refer to them that way - especially as we may add, remove, or move around form elements. For example, a form with id LoginForm can be referenced as document.getElementById('LoginForm'). The major advantage of referencing forms by id is that the forms can be repositioned on the page without affecting the JavaScript.

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



But we can access form elements by their ids, too, just as we can forms - it's concise, simple, and clear.

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>
function changeBg(){
		var userName = document.getElementById("userName").value;
		var backgroundClr = document.getElementById("color").value; = backgroundClr;
		alert(userName + ", the background color is " + backgroundClr + ".");

	window.onload = function() {
		document.getElementById("changebutton").addEventListener("click", function(){
<h1>Change Background Color</h1>
<form name="colorForm">
	Your Name: <input type="text" name="userName" id="userName"><br>
	Background Color: <input type="text" name="color" id="color"><br>
	<input type="button" value="Change Background" id="changebutton">

Code Explanation

Some things to notice:

  1. When the user clicks on the "Change Background" button, the changeBg() function is called. Note how we added a click handler via the addEventListener() method: whereas earlier in the course we used the onclick attribute on the button itself to call a JavaScript function, we now use addEventListener() to call the function. Separating the event handler from the element makes for cleaner, more-easily-maintainable code. Similarly, we call the onload method using window.onload(), rather than (as we had done previously) adding an attribute to the body tag.
  2. The values entered into the userName and color fields are stored in variables (userName and backgroundClr).
  3. We reference the two fields directly via their ids.

This tutorial is based on Webucator's Introduction to JavaScript Training Course. We also offer many other JavaScript Training courses. Sign up today to get help from a live instructor.