JavaScript Chapter 7 Javascript and HTML Forms

Javascript and HTML Forms

You can use Javascript to check that form elements have been filled in correctly. If not, you can keep your users on the same page and display an error message. If everything is OK then you can submit the form. You'll see how that works now.
Instead of you having to type out the HTML for the form on the web page, download ours here:
The form is a text file, so you'll need to save it to your computer as basic_form.html rather than the basic_form.txt file it is now.
The HTML, then, is this:
A HTML form
The first thing to notice is the FORM tag itself:
We have given the form the name frmOne. We'll be using this name in our Javascript. We've also left the ACTION attribute blank. But in a real world situation this would be the name of a processing script like form_validate.php. Or you could have an email address for the ACTION. This, however, is not recommended as spammers have bots trawling the net for email addresses in HTML pages. For further information about ACTION and METHOD, see our web design course.
The form elements we're going to be testing are the text box elements, radio buttons (sometimes called option buttons), dropdown lists, and check boxes.
Each element on our form also has a NAME attribute. To go with each element we have a SPAN tag. The SPAN tags have a CSS colour and an ID. We'll be using these SPAN tags to display error messages.
The Submit button has an onClick event. This event will activate a function that we've calledvalidate.
Our rather messy form, then, looks like this in a browser:
The form in a browser

The validate function

The only thing our Javascript will be doing is checking to see if users have filled out the form correctly. The strategy we'll take is this:
  • Set up four functions, one for each form element
  • Return a value of true or false from these functions. A value of true will mean everything's OK, while a value of false will mean an error has been detected.
  • The true or false values returned from the functions will be checked in an IF Statement. If all the values are true it means all form elements have been filled in correctly. So we can go ahead and send the form. If just one of them is false then the form will not be sent.
So add a function called validate in between your two SCRIPT tags. In between the curly brackets of the validate function, add the following four variables and function calls:
function validate() {
var emailError = checkEmail();
var radioError = checkRadio();
var dropdownError = checkDropdown();
var checkboxError = checkCheckbox();
The four variables are emailErrorradioErrordropdownError, and checkboxError. To the right of these variables we have four function calls: checkEmailcheckRadiocheckDropdown, andcheckCheckbox. Once a value has been returned from these function the variables will be either true or false. We'll add the IF Statement that checks these values later.
First up is the email function. However, we'll take a short diversion and examine something calledgetElementById. This is a very useful method of the document object.

Using getElementById in Javascript

The document method getElementById is used to manipulate particular HTML elements on your page. As its name suggests, though, the HTML element needs an ID attached to it. As an example, take a look at this segment of a web page:
So we have a textbox and a button. When the button is clicked, we want to make sure that the textbox has been filled in. If it's still blank then we don't want to send the form anywhere. We can keep the user on the same page and colour the textbox, say, red. This will offer a visual clue that the textbox needs to be filled in. Here's what the textbox will look like if it's left blank and the button is clicked:
The code for all this makes use of getElementById. Here it is:
Use of getElementById in Javascript
In the BODY section of the HTML we have a textbox and a button. But notice the highlighted ID for the textbox:
So we've attached an ID to this HTML element. We then use this ID with the following: (Don't worry about the IF Statement - you'll study those soon.)
if ( document.getElementById("textbox_1").value=='' ) {
The getElementById method needs a pair of round brackets. In between these round brackets you type the ID you're trying to access. The ID needs to be surrounded by quote marks, single or double. Textboxes have a VALUE attribute. You can get at this value by adding it after the round brackets (type a dot first, though). We then have two equal symbols. To specify a blank value in the text box, we have two single quote marks (we could have used doubles, though).
One thing to be aware of for getElementById is that the "d" of "Id" is lowercase but the "I" is uppercase. So it's not "ID" but "Id". Get that bit wrong and your code won't work.
To change the textbox red, our code is this:
So we are still accessing the ID of the textbox. This time, we're adding a style after the round brackets:
The particular style we're changing is the background colour.

Javascript Form Validation - the email function

We'll start with the function that checks the email address text box. We'll only check if the text box has had anything typed into it. Checking for a correct email address is notoriously difficult, so we're just trying to keep things simple here.
Add the following function to your code (you won't be able to copy and paste because ours is an image - you'll learn more if you type it out for yourself):
A check email function
Your script tags should now look like this:
The email and validate functions
The first line of the checkEmail function is this:
var email =;
Previously, we got a reference to a text box by using getElementById. Another way to access form elements is to use the following syntax:
Our form was called frmOne, so we start with document.frmOne. The element name you're trying to access comes next. In the HTML, we gave our text box element the name email. If you want to get what was in the text box, you need the value attribute at the end.
So we're getting the text value from the text box and storing it in a variable called email.
The IF statement tests what is in this variable. We're only testing for a blank value (two double quotes with no spaces between them, though you can single quotes instead of doubles). If email is blank then two things happen:
document.getElementById("email_error").innerHTML = "No Email Address";
return false;
We're using getElementById to access an HTML element with the ID "email_error". Notice that we're also using innerHTML after getElementById. The inner HTML is anything between two tags. So if you had <P>Some inner text</P> then the innerHTML would be "Some inner text". After an equal sign we're resetting the innerHTML and replacing it with the text "No Email Address".
The next line is return false. This is enough to set the whole of the function to false.
If the text box is not blank we set the innerHTML again, this time to a blank string. The return value is then true.
You can try your script out now. Don't type anything in the email text box. Just click the submit button. You should see this:
Email error message
Now type something in the text box. Click the submit button again and the red error message should go away.

Radio Buttons

Checking radio buttons on a form is a little trickier. You have to loop through each button, testing for a value of checked, which means it was selected. Only one radio button in a group can be selected, so if you find a value of checked you can break out of the loop.
If no radio button was checked then you can return a value of false. If any one of them is checked then you can return a value of true. Here's the code for your radio button function:
Javascript function to check radio buttons
First we set up a variable called payment and set it to be a blank string. This will hold a value of checked if the user has selected a radio button and will be empty otherwise. The next line is this:
var len = document.frmOne.payment.length;
On the right of the equal sign we again try to access a form element. This time, the element we want has a name of payment. This came from the HTML:
<INPUT TYPE="Radio" Name="payment" Value="CC">Credit Card
<INPUT TYPE="Radio" Name="payment" Value="DC">Debit Card
<INPUT TYPE="Radio" Name="payment" Value="PP">PayPal
If you want to group radio buttons together you give them the same name. You can then access this name in your code. But look at what is now on the end:
When we accessed the text box element like this we had value on the end. This time we have length. Length is how many radio button are in the group. We can use this length in the loop:
for (i = 0; i < len; i++) {
if ( document.frmOne.payment[i].checked ) {
payment = document.frmOne.payment[i].value;
The loop goes round and around while the variable called i is less than the length of the radio buttons. Inside of the loop we have this:
if ( document.frmOne.payment[i].checked ) {
payment = document.frmOne.payment[i].value;
This IF statements checks each radio button for a value of checked. But we can't just say:
The payment part refers to the whole group of radio buttons. To get at each individual radio button you can use a pair of square brackets. Inside the square brackets you type a number. The number corresponds to a particular button. So payment[0] is the first button, payment[1] is the second button, and so on. If the IF statement detects that any one of these buttons has a value of checked it puts that value into the payment variable:
payment = document.frmOne.payment[i].value;
We can then break out of the loop because we know that the user has selected a radio button.
The IF statement after the loop checks what's inside the variable called payment. It does exactly the same thing as the email check box. The only difference is that it places an error message besides the radio buttons rather than besides the text box.
Test it out. Click your submit button without selecting a radio button. You should see this:
Testing for errors in radio buttons
Now select a payment option. Click the button again and the error message will disappear.

Dropdown Lists

The code to check the dropdown list is more or less the same as for radio buttons. Here it is:
Javascript code to check a dropdown lists
The only difference is in the IF Statement. Between the round brackets we have the following:
Dropdown lists have a selected property at the end. This means whether an item was selected from the list or not. Again, we're looping over all of the items. Whichever item was chosen will be placed in the variable called chosen. But it's the value property we want to place in the variable. This gets you the text of the item on the list.
We want to detect if the user has left it on the default option of "None". If so, it's an error and we can ask the user to try again.
Test your code out. Don't select an item from the list. When you click the submit button you should see this:
Displaying and error message for a dropdown lists
Select an item and then click the button again. The error message will vanish.


The final function we need is for the checkbox. You can have 1 or more checkboxes on a form. We only have 1, so checking it is fairly straightforward. If you have more than checkbox, though, you do the testing in exactly the same way as for radio buttons.
But here's the code for the checkCheckbox function:
Javascript code to test a checkbox
The IF statement just tests the terms HTML element (a checkbox) for a value of checked. If it has been checked then we can return a value of true, as the user has agreed to the terms and conditions. If the checkbox has not been checked, the value will be "undefined" and we can return a value of false.
Test it out. Leave the check box unchecked. Click the submit button and you'll see this:
checkbox error message
When you check the box the error message should disappear.

Validating the HTML form

The only thing left to do is to return to the validate function. After all the other four functions have been executed, the four variables will either be true or false. We only want to send the form if all four variables are true. If they are not then the user has made an error and we need to keep them on the same page. Here's the rest of the code for the validate function:
Javascript code to validate a HTML form
The new part is the IF … ELSE statement. It's uses the AND operator (&&) three times. IF all four variables are true we have this line:
You only need the word submit with a pair of round brackets on the end. This is enough to send the form to whatever you have for the ACTION attribute for the FORM tag.
If you don't want to send the form the only thing you need to do is to set the return value to false.