Handling forms
Objectives
- write code to require a field on a form
- write code to compare two fields on a form
- use an image as a submit button
- use a drop-down list for navigation
- modify a drop-down list using JavaScript
Special note for HTML5
HTML5 has new form elements and some automatic validation. These notes cover
pre-HTML5 forms since there is still a lot of variation in what browsers
support as these notes are being written.
Preliminaries
It would be useful to have a page we go to after the form is validated. Getting
to that page would provide a clear indication that the validation code let the
data through, while not getting to the page would make it clear that something
didn't validate. For the sake of today's demonstrations, we will name this file
receiver.html. The code is as follows:
<html>
<head>
<title></title>
</head>
<body>
<h2>I received your message</h2>
</body>
</html>
Note on more modern technique
The examples on this page show a number of ways of accessing form field values.
In almost all cases, it is now preferable to give fields an ID value and then
get a reference to them using document.getElementById(). Both the older and
newer styles are included in the examples on this page.
Requiring a form field
- Validating data using JavaScript is intended to speed up validation
and to make for a more pleasant user experience. Do NOT use it for security
purposes or assume that the data is valid when it reaches the server.
The JavaScript code can easily be bypassed.
- Use the form element's onsubmit event handler to take care of validation.
Return true to submit form, false to cancel the submission.
- You can place the cursor in a field by using the "focus" method of
that element (eg. f.passwd.focus(); or document.forms["frm1"]["passwd"].focus();).
- The code demonstrated in the first example uses the this
variable to send a form element reference to the validation function.
- Please note that this is NOT a good way to send a password across the Internet.
You can see the lask of encryption by looking at the URL since this form
uses the GET method. Using the POST method would keep the password out of
the URL, but would still not have encryption and the password would be
plainly visible to anyone who was eavesdropping.
- In the following code, the password field is required, but the login
field is not (see form1.html):
<html>
<head>
<title></title>
<script>
function validate() {
var f = document.getElementById('frm1');
if (f.passwd.value == "") {
alert("Password field must be supplied");
f.passwd.focus();
return false;
}
return true;
}
window.onload = function() {
document.getElementById('frm1').onsubmit = validate;
}
</script>
</head>
<body>
<form action="receiver.html" method="get" name="frm1" id="frm1">
Login: <input type="text" name="login" id="login" /><br />
Password: <input type="password" name="passwd" id="passwd" /><br />
<input type="reset" value="Clear Form" />
     
<input type="submit" value="Send Me" />
</form>
</body>
</html>
- A nicer version of the previous example (see
form1b.html):
<html>
<head>
<title></title>
<script>
window.onload = initValidate;
function initValidate() {
document.forms["frm1"].onsubmit = validate;
}
function validate() {
var myform = document.forms["frm1"];
if (myform["passwd"].value == "") {
alert("Password field must be supplied");
myform["passwd"].focus();
return false;
}
return true;
}
</script>
</head>
<body>
<form action="receiver.html" method="get" name="frm1" id="frm1" style="width:3em;">
<fieldset>
<legend>Login</legend>
<table>
<tr>
<td><label for="login">Login: </label></td>
<td><input type="text" name="login" id="login" /><br /></td>
</tr>
<tr>
<td><label for="passwd" style="width:10em;">Password: </label></td>
<td><input type="password" name="passwd" id="passwd" /><br /></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="reset" value="Clear Form" />
<input type="submit" value="Send Me" />
</td>
</tr>
</table>
</fieldset>
</form>
</body>
</html>
- A more modern version of the previous example (see
form1c.html):
<html>
<head>
<title></title>
<script>
window.onload = initValidate;
function $(id) {
return document.getElementById(id);
}
function initValidate() {
$('frm1').onsubmit = validate;
}
function validate() {
if ($('passwd').value == "") {
alert("Password field must be supplied");
$('passwd').focus();
return false;
}
return true;
}
</script>
</head>
<body>
<form action="receiver.html" method="get" name="frm1" id="frm1" style="width:3em;">
<fieldset>
<legend>Login</legend>
<table>
<tr>
<td><label for="login">Login: </label></td>
<td><input type="text" name="login" id="login" /><br /></td>
</tr>
<tr>
<td><label for="passwd" style="width:10em;">Password: </label></td>
<td><input type="password" name="passwd" id="passwd" /><br /></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="reset" value="Clear Form" />     
<input type="submit" value="Send Me" />
</td>
</tr>
</table>
</fieldset>
</form>
</body>
</html>
Comparing form fields
- This example is similar to the last, except that the password
must be entered twice and both entries must match.
- You can manually set a text field using the "value" property
- f.passwd1.value = "";
- document.forms["frm1"]["passwd1"].value = "";
- document.getElementById("passwd1").value = "";
- You can select everything in a text field using the "select" function
- f.passwd1.select();
- document.forms["frm1"]["passwd1"].select();
- document.getElementById("passwd1").select();
- Here's the code (see form2.html):
<html>
<head>
<title></title>
<script>
function validate() {
var f = document.getElementById('frm1');
if (f.passwd1.value == "") {
alert("Password is required");
f.passwd1.focus();
return false;
}
if (f.passwd1.value != f.passwd2.value) {
alert("Passwords do not match");
f.passwd1.value = "";
f.passwd2.value = "";
f.passwd1.focus();
return false;
}
return true;
}
window.onload = function() {
document.getElementById('frm1').onsubmit = validate;
}
</script>
</head>
<body>
<form action="receiver.html" method="get" name="frm1" id="frm1">
Login: <input type="text" name="login" id="login" /><br />
Password: <input type="password" name="passwd1" id="passwd1" /><br />
Password: <input type="password" name="passwd2" id="passwd2" /><br />
<input type="reset" value="Clear Form" />
     
<input type="submit" value="Send Me" />
</form>
</body>
</html>
- A nicer version of the previous example (see
form2b.html):
<html>
<head>
<title></title>
<script>
window.onload = initValidate;
function initValidate() {
document.forms["frm1"].onsubmit = validate;
}
function validate() {
var myform = document.forms["frm1"];
if (myform["passwd1"].value == "") {
alert("Password is required");
myform["passwd1"].focus();
return false;
}
if (myform["passwd1"].value != myform["passwd2"].value) {
alert("Passwords do not match");
myform["passwd1"].value = "";
myform["passwd2"].value = "";
myform["passwd1"].focus();
return false;
}
return true;
}
</script>
</head>
<body>
<form action="receiver.html" method="get" name="frm1" id="frm1" style="width:3em;">
<fieldset>
<legend>Login</legend>
<table>
<tr>
<td><label for="login">Login: </label></td>
<td><input type="text" name="login" id="login" /><br /></td>
</tr>
<tr>
<td><label for="passwd1" style="width:10em;">Password: </label></td>
<td><input type="password" name="passwd1" id="passwd1" /><br /></td>
</tr>
<tr>
<td><label for="passwd2" style="width:10em;">Password: </label></td>
<td><input type="password" name="passwd2" id="passwd2" /><br /></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="reset" value="Clear Form" />
<input type="submit" value="Send Me" />
</td>
</tr>
</table>
</fieldset>
</form>
</body>
</html>
- A nicer more modern version of the previous example (see
form2c.html):
<html>
<head>
<title></title>
<script>
window.onload = initValidate;
function $(id) {
return document.getElementById(id);
}
function initValidate() {
$('frm1').onsubmit = validate;
}
function validate() {
if ($('passwd1').value == "") {
alert("Password is required");
$('passwd1').focus();
return false;
}
if ($('passwd1').value != $('passwd2').value) {
alert("Passwords do not match");
$('passwd1').value = "";
$('passwd2').value = "";
$('passwd1').focus();
return false;
}
return true;
}
</script>
</head>
<body>
<form action="receiver.html" method="get" name="frm1" id="frm1" style="width:3em;">
<fieldset>
<legend>Login</legend>
<table>
<tr>
<td><label for="login">Login: </label></td>
<td><input type="text" name="login" id="login" /><br /></td>
</tr>
<tr>
<td><label for="passwd1" style="width:10em;">Password: </label></td>
<td><input type="password" name="passwd1" id="passwd1" /><br /></td>
</tr>
<tr>
<td><label for="passwd2" style="width:10em;">Password: </label></td>
<td><input type="password" name="passwd2" id="passwd2" /><br /></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="reset" value="Clear Form" />     
<input type="submit" value="Send Me" />
</td>
</tr>
</table>
</fieldset>
</form>
</body>
</html>
Using an image to submit a form
- This example shows how images can be used in place of reset
and submit buttons. The submission and clearing of the form
is done with code.
- Both of these examples show bad style by including inline JavaScript code
for the two image links with no fallback.
- You can set a form back to default values using the form's "reset" function
- You can submit a form through code using the form's "submit" function
- The submit image is available: submit.gif
- The clear image is available: clear.gif
- Here's the code (see form3.html):
<html>
<head>
<title></title>
<script>
window.onload = initValidate;
function initValidate() {
document.forms["frm1"].onsubmit = validate;
}
function validate() {
var f = document.forms["frm1"];
if (f["passwd1"].value == "") {
alert("Password is required");
f["passwd1"].focus();
return false;
}
if (f["passwd1"].value != f["passwd2"].value) {
alert("Passwords do not match");
f["passwd1"].value = "";
f["passwd2"].value = "";
f["passwd1"].focus();
return false;
}
return true;
}
function doreset() {
var f = document.forms["frm1"];
f.reset();
f["login"].focus();
}
function dosubmit() {
var f = document.forms["frm1"];
if (validate()) f.submit();
}
</script>
</head>
<body>
<form action="receiver.html" method="get" name="frm1" id="frm1" style="width:3em;">
<fieldset>
<legend>Login</legend>
<table>
<tr>
<td><label for="login">Login: </label></td>
<td><input type="text" name="login" id="login" /><br /></td>
</tr>
<tr>
<td><label for="passwd1" style="width:10em;">Password: </label></td>
<td><input type="password" name="passwd1" id="passwd1" /><br /></td>
</tr>
<tr>
<td><label for="passwd2" style="width:10em;">Password: </label></td>
<td><input type="password" name="passwd2" id="passwd2" /><br /></td>
</tr>
<tr>
<td colspan="2" align="center">
<a href="javascript:void doreset();"><img src="clear.gif" border="0" /></a>
<a href="javascript:void dosubmit();"><img src="submit.gif" border="0" /></a>
</td>
</tr>
</table>
</fieldset>
</form>
</body>
</html>
- Here's a more modern version of the code (see form3b.html):
<html>
<head>
<title></title>
<script>
window.onload = initValidate;
function $(id) {
return document.getElementById(id);
}
function initValidate() {
$('frm1').onsubmit = validate;
}
function validate() {
if ($('passwd1').value == "") {
alert("Password is required");
$('passwd1').focus();
return false;
}
if ($('passwd1').value != $('passwd2').value) {
alert("Passwords do not match");
$('passwd1').value = "";
$('passwd2').value = "";
$('passwd1').focus();
return false;
}
return true;
}
function doreset() {
$('frm1').reset();
$('login').focus();
}
function dosubmit() {
if (validate()) $('frm1').submit();
}
</script>
</head>
<body>
<form action="receiver.html" method="get" name="frm1" id="frm1" style="width:3em;">
<fieldset>
<legend>Login</legend>
<table>
<tr>
<td><label for="login">Login: </label></td>
<td><input type="text" name="login" id="login" /><br /></td>
</tr>
<tr>
<td><label for="passwd1" style="width:10em;">Password: </label></td>
<td><input type="password" name="passwd1" id="passwd1" /><br /></td>
</tr>
<tr>
<td><label for="passwd2" style="width:10em;">Password: </label></td>
<td><input type="password" name="passwd2" id="passwd2" /><br /></td>
</tr>
<tr>
<td colspan="2" align="center">
<a href="javascript:void doreset();"><img src="clear.gif" border="0" /></a>
     
<a href="javascript:void dosubmit();"><img src="submit.gif" border="0" /></a>
</td>
</tr>
</table>
</fieldset>
</form>
</body>
</html>
- Here's an improved version which uses "button" elements. (see form3c.html):
<html>
<head>
<title></title>
<script>
function $(id) {
return document.getElementById(id);
}
function validate() {
if ($('passwd1').value == "") {
alert("Password is required");
$('passwd1').focus();
return false;
}
if ($('passwd1').value != $('passwd2').value) {
alert("Passwords do not match");
$('passwd1').value = "";
$('passwd2').value = "";
$('passwd1').focus();
return false;
}
return true;
}
window.onload = function() {
$('frm1').onsubmit = validate;
$('frm1').onreset = function() { $('login').focus(); };
}
</script>
</head>
<body>
<form action="receiver.html" method="get" name="frm1" id="frm1" style="width:3em;">
<fieldset>
<legend>Login</legend>
<table>
<tr>
<td><label for="login">Login: </label></td>
<td><input type="text" name="login" id="login" /><br /></td>
</tr>
<tr>
<td><label for="passwd1" style="width:10em;">Password: </label></td>
<td><input type="password" name="passwd1" id="passwd1" /><br /></td>
</tr>
<tr>
<td><label for="passwd2" style="width:10em;">Password: </label></td>
<td><input type="password" name="passwd2" id="passwd2" /><br /></td>
</tr>
<tr>
<td colspan="2" align="center">
<button type="reset"><img src="clear.gif" border="0" /></button>
     
<button type="submit"><img src="submit.gif" border="0" /></button>
</td>
</tr>
</table>
</fieldset>
</form>
</body>
</html>
Drop down list navigation
- This page demonstrates how to use a drop down list for navigation. This does not address
accessibility issues that may be raised by doing this, although this code does allow for
browsers which have JavaScript disabled.
- When JavaScript is disabled, the "noscript" tag inserts a submit button for the form.
Clicking on that button will cause the form to submit its data to the file specified in the
form's action value. In this case, that is a PHP script which redirects to the specified page.
The PHP script is as follows:
<?php
header('Location: ' . $_GET['loclist']);
?>
- You can access the items on a list using an index into the list's options array (eg.
document.frm1.loclist.options[1]
or document.forms["frm1"]["loclist"].options[1]).
- You can access the value of an item on a list using the value property of that item
(eg. document.frm1.loclist.options[1].value or
document.forms["frm1"]["loclist"].options[1].value).
- You can set which item on a list is selected using the list's "selectedIndex"
property (eg. document.frm1.loclist.selectedIndex = 2; or
document.forms["frm1"]["loclist"].selectedIndex = 2;]).
- You can find out which item on a list is selected using the list's "selectedIndex"
property (eg. n = document.frm1.loclist.selectedIndex; or
n = document.forms["frm1"]["loclist"].selectedIndex;).
- See form4.html:
<html>
<head>
<title></title>
<script>
function jump() {
var lst = document.forms["frm1"]["loclist"];
var dest = lst.options[lst.selectedIndex].value;
if (dest != "") window.location = dest;
}
window.onload = function() {
document.forms["frm1"]["loclist"].selectedIndex = 0;
document.forms["frm1"]["loclist"].onchange = jump;
};
</script>
</head>
<body>
<form action="gotoLocation.php" method="get" name="frm1" id="frm1">
<select name="loclist" id="loclist">
<option selected="selected" value="">Choose a location</option>
<option value="receiver.html">receiver</option>
<option value="form1.html">form1</option>
<option value="form2.html">form2</option>
<option value="form3.html">form3</option>
</select><br />
<noscript>
<input type="submit" value="Go" />
</noscript>
</form>
</body>
</html>
- Here's a more modern version (see form4b.html):
<html>
<head>
<title></title>
<script>
function $(id) {
return document.getElementById(id);
}
function jump() {
if ($('loclist').value != "") window.location = $('loclist').value;
}
window.onload = function() {
$('loclist').selectedIndex = 0;
$('loclist').onchange = jump;
};
</script>
</head>
<body>
<form action="gotoLocation.php" method="get" name="frm1" id="frm1">
<select name="loclist" id="loclist">
<option selected="selected" value="">Choose a location</option>
<option value="receiver.html">receiver</option>
<option value="form1.html">form1</option>
<option value="form2.html">form2</option>
<option value="form3.html">form3</option>
</select><br />
<noscript>
<input type="submit" value="Go" />
</noscript>
</form>
</body>
</html>
Modifying a drop down list
- This demonstrates how one drop down list can be modified when
another drop down list has been changed.
- Notice how this code depopulates a list first by setting all
options to null, and then repopulates the options using the
data from an array.
- The body's onload event has been used to try to make sure that
users returning to the form have their page reset. Otherwise you
end up with screwy things like having a country selected in one
drop down list while no cars appear in the other list.
- See form5.html:
<html>
<head>
<title></title>
<script type="text/javascript">
function initForm() {
document.forms["frm1"].onsubmit = validate;
document.forms["frm1"].onreset = function() {
clearItems();
document.forms["frm1"]["country"].selectedIndex=0;
};
document.forms["frm1"].reset();
document.forms["frm1"]["country"].onchange = changeCars;
}
var cArray = new Array();
cArray["German"] = new Array("VW", "Audi", "Mercedes", "BMW");
cArray["American"] = new Array("Chevrolet", "Chrysler", "Ford", "Mercury", "Buick");
function clearItems() {
var i = document.forms["frm1"]["cars"].length;
while (i > 1) {
document.forms["frm1"]["cars"].options[--i] = null;
}
}
function changeCars() {
var lst = document.forms["frm1"]["country"];
clearItems();
if (lst.selectedIndex != 0) {
val = lst.options[lst.selectedIndex].value;
len = cArray[val].length;
for (var i=0; i<len; i++) {
document.forms["frm1"]["cars"].options[i+1] =
new Option(cArray[val][i]);
}
}
}
function validate() {
var f = document.forms["frm1"];
if (f["country"].selectedIndex == 0) {
alert("You must select a country");
f["country"].focus();
return false;
}
if (f["cars"].selectedIndex == 0) {
alert("You must select a car");
f["cars"].focus();
return false;
}
return true;
}
window.onload = initForm;
</script>
</head>
<body>
<form action="receiver.html" method="get" name="frm1" id="frm1">
<select name="country" id="country">
<option selected="selected">Choose a country</option>
<option value="German">German</option>
<option value="American">American</option>
</select>
<select name="cars" id="cars">
<option>Choose an item</option>
</select>
<p> </p>
<input type="reset" />
<input type="submit" />
</form>
</body>
</html>
- For a more modern version see form5b.html:
<html>
<head>
<title></title>
<script>
function $(id) {
return document.getElementById(id);
}
function initForm() {
$('frm1').onsubmit = validate;
$('frm1').onreset = function() {
clearItems();
$('country').selectedIndex=0;
};
$('frm1').reset();
$('country').onchange = changeCars;
}
var cArray = new Array();
cArray["Germany"] = new Array("VW", "Audi", "Mercedes", "BMW");
cArray["America"] = new Array("Chevrolet", "Chrysler", "Ford", "Mercury", "Buick");
function clearItems() {
var i = $('cars').length;
while (i > 1) {
$('cars').options[--i] = null;
}
}
function changeCars() {
var lst = $('country');
clearItems();
if (lst.selectedIndex != 0) {
var val = lst.options[lst.selectedIndex].value;
var len = cArray[val].length;
for (var i=0; i<len; i++) {
$('cars').options[i+1] = new Option(cArray[val][i]);
}
}
}
function validate() {
if ($('country').selectedIndex == 0) {
alert("You must select a country");
$('country').focus();
return false;
}
if ($('cars').selectedIndex == 0) {
alert("You must select a car");
$('cars').focus();
return false;
}
return true;
}
window.onload = initForm;
</script>
</head>
<body>
<form action="receiver.html" method="get" name="frm1" id="frm1">
<select name="country" id="country">
<option selected="selected">Choose a country</option>
<option value="Germany">Germany</option>
<option value="America">America</option>
</select>
<select name="cars" id="cars">
<option>Choose a car</option>
</select>
<p> </p>
<input type="reset" />     
<input type="submit" />
</form>
</body>
</html>