HTML and CSS Reference
In-Depth Information
JavaScript code to indicate the value that will be sent back. Our example will return a
value of
true
if the data is valid, the function will return a value of
true
and a value of
false
if the data does not pass our validation tests. Notice that the
onsubmit
event
handler also contains the keyword
return
. It works like this: if the
validateForm()
function returns a value of
true
, the
onsubmit
event handler becomes
return true
and the form is submitted. If the
validateForm()
function returns a value of
false
,
the
onsubmit
event handler becomes
return false
and the form is not submitted.
Once a function returns a value, it is finished executing regardless of whether or not
there are more statements in the function.
HANDS-ON PRACTICE 14.8
In this Hands-On Practice you will create a form with inputs for name and age, and use
JavaScript to validate the data such that there will be data in the name field and an age
of 18 or greater. If there is nothing in the name field, an alert message will be displayed
instructing the user to enter a name. If the age entered is less than 18, an alert message
will be displayed instructing the user to enter an age of 18 or greater. If all data is valid,
an alert message will be displayed indicating that the data is valid and the form will be
submitted.
Let's start by creating the form. Open a text editor and type the following. Notice that
the
onsubmit
form handler is embedded in the
<form>
tag and we will add the
JavaScript code later. CSS is used to align and add space around the form elements.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title>JavaScript Practice</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style type="text/css">
div { padding-bottom: 10px;
width: 250px;
text-align: right; }
label { padding-right: 5px; }
</style>
</head>
<body>
<h1>JavaScript Form Handling</h1>
<form method="post"
action="http://webdevfoundations.net/scripts/formdemo.asp"
onsubmit="return validateForm();">
<div>
<label for="userName">Name:</label>
<input type="text"
name="userName" id="userName"
/>
</div>
Search WWH ::
Custom Search