JavaScript: Forms

Reading HTML 9.14-9.33

When forms were added to HTML, one of the first problems was validation. Without JavaSCript, the user would fill out the form, click on the Submit button and wait. The contents of the form were sent off to the server, a CGI program was run on the information sent and the program would first check that all the fields were filled in.

Then, if something was missing, the program would create a new web page explaining the error. This would be sent back to the browser and displayed. The user would see this, be irritated and click on the back button to get back to the form. And sometimes, the form would be blank and they would have to start over.

With JavaScript, we can check the contents of the form before it is submitted. If there is an error, we can display a message, and put the focus back on the form element in error. Only after the form is validated will it be submitted to the server. A much more pleasant experience.

First we have to find the elements on the page. In the discussion of the DOM we learned about the method getElementByID() to find elements on the page. Forms are a little easier. The browser keeps track of forms for us. The easiest way to do this is to give all form elements and the form names. For example,

<form method="post" 
		name="form1" 
		action="http://www.archie-perkins.com/teaching/devry/comp313/formtest.pl" 
		onSubmit='return checkform();'>
		 Enter your first name
		 <input type="text" name="fname"><br>
		 Enter your last name
		 <input type="text" name="lname"><br>
		 Enter a phone number in this format (555) 555-1234
		 <input type="text" name="phone"><br>
		 <input type="submit">
<form>

Now we can access the form and elements directly. To see what is in the first name field all we need is

var fname = document.form1.fname.value;

There are several other properties and methods on form elements. To change the value in a text field, we would do

document.form1.fname.value ="new stuff";
We can set the focus on a form element. The focus is where the attention of the browser is fixed. If we set the focus on a text field, then the next thing we type is put into the field. It is a lot like what happens when we click on a field.
document.form1.fname.focus();

Let's look at an example that combines some of these operations with some string handling to validate a form.