overview
The form we made yesterday is easily misused. Someone may leave a required field blank, or construct their email address incorrectly. It's important to make sure that any information we store in our database is in the correct format. Today, we'll use javascript to examine the form for any errors, and let our user know where the errors are. We'll also get an idea of how javascript works in general.
quiz/discussion
Javascript is a scripting language that can be used on web pages and executed by the visitor. It's different than php or python, as those languages run on the web server.
One nice thing about Javascript is that the server doesn't have to do any work. A bad thing is that users can turn off Javascript, leaving your form management efforts defunct. For most cases, Javascript is the best way to validate submitted data. However, critical information should always be handled by server-side scripts.
It's a good idea to label required fields with a bold red asterisk (*), but often designers make everything required out of laziness. Remedy: Think hard about whether you really need to know if someone is a Mr. or a Mrs. or a Ms. Users appreciate having to enter as little info as possible.
Javascript elements are added to your page using the script tag, the type attribute, and the text/javascript value. They can be inserted anywhere in your page, between the html tags. Keep in mind that JavaScripts in the body section will be executed WHILE the page loads. JavaScripts in the head section will be executed when CALLED.
Basic syntax: document.write("hello world");
Comments
Variables -- strings and numbers (If you add a number and a string, the result will be a string.)
Operators-arithmetic, assignment, comparison
Conditionals/switch
Popups
Functions
Loops
Events
Events occur whenever somehting happens. Often this is because of the user-who may click a link, resize the window, hover over an element. All of these things are triggers, or events. Events include (adapted from w3schools):
| Attribute | Occurs when... |
|---|---|
| onblur | An element loses focus |
| onchange | The user changes the content of a field |
| onfocus | An element gets focus |
| onkeydown | A keyboard key is pressed |
| onkeypress | A keyboard key is pressed or held down |
| onkeyup | A keyboard key is released |
| onreset | The reset button is clicked |
| onsubmit | The submit button is clicked |
The events listed above are all instigated by the user, but <body onload="myFunction"> is an example of an event that gets triggered automatically whe a web page loads.
When a user interacts with a form, lots of events are happening. Javascript can react to any of these events. We will examine the onsubmit event, which occurs when the user submits the form.
When this happens, the information typed in and checked is suspect and should be considered guilty until proven innocent. Most of the time, erroneous information submitted is benign; the user forgets to enter her email address, or only types in 4 numbers for her zip. However, forms can be targeted by malicious users and robots to serve spam harvesting efforts. With javascript, you can steer users in the right direction and fend off attacks from the bad guys.
We can use javascript to tell the browser not to submit the form if anything is screwed up. The first step in doing this is to add an onsubmit attribute to the opening form tag.
Here's the code:
<form name="contact_form" method="post" action="#" onsubmit="return validate ( );"> First Name: <input type="text" name="first_name"><br/> Last Name: <input type="text" name="last_name"><br/> Email:<input type="text" name="email"><br/> <input type="submit" name="submit" value="Send it in!"> </form>
Rendered in browser:
The onsubmit attribute tells the browser to do something when the form is submitted. In this case, return whatever value comes out during the validate() function. If validate() returns true, the form is sent. If false, the form does not get sent.
A function is like a mini-program. Here, we can construct the function in just a few lines:
<script type="text/javascript">
function validate ( )
{
valid = true;
if ( document.contact_form.first_name.value == "" )
{
alert ( "Please enter your first name." );
document.contact_form.first_name.focus();
valid = false;
}
return valid;
}
</script>
We start by using script tags to tell the browser that this is a script, specifically, text/javascript. Then we create a function, give it a name and a pair of empty parenthesis, an opening hitchcock, a series of instructions, and a closing hitchcock.
Inside the script, we start with a variable called "valid", and set it's value to true.
valid = true;
Then we check to see if the first name field is empty
if ( document.contact_form.first_name.value == "" )
the stuff inside the parens there is dot syntax; from left to right, connected with dots, is a path to the value entered in the first_name field in the contact_form form in the document. == is a programming convention for comparing things; we compare the value to a pair of empty quotes, or nothing.
If it's true that the value of first_name is nothing, then the stuf between the next set of hitchcocks gets executed. A javascript alert box opens with a message telling the user they screwed up:
alert ( "Please enter your first name." );
The dot-syntax is used with a focus method (methods appear with () after are verbs, they occur like jump or bark)
document.contact_form.first_name.focus();
And the valid variable is set to false:
valid = false;
Once this has all occurred, the value of "valid" is returned.
This is a very simple script. We could easily add more if statements to the function to test for the other fields. But if the user forgets to fill out more than one field, they will be notified over and over again until all the fields are filled in.
Of course, there are more complex scripts to handle such scenarios more gracefully. Google away, you'll find millions. Most are built on a the idea of the basic loop--
{
document.write("The field name is: " + document.FormName.elements[i].name + " and it's value is: " + document.FormName.elements[i].value + ".<br />");
}
discussion
View the page Sample Form, and walk through the code with me.
lab
Write a script that checks each of your form elements and checks to make sure they have not been left empty.