Home and Learn: Javascript Programming Course
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:
The first thing to notice is the FORM tag itself:
<FORM NAME="frmOne" ACTION="" METHOD="POST">
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 called validate.
Our rather messy form, then, looks like this in a browser:
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:
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 emailError, radioError, dropdownError, and checkboxError. To the right of these variables we have four function calls: checkEmail, checkRadio, checkDropdown, and checkCheckbox. 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 called getElementById. This is a very useful method of the document object. We'll do that in the next section.
< Customised Dates | getElementById >
Email us: enquiry at homeandlearn.co.uk