Web Development and Design Foundations with XHTML, 5th Edition

(Steven Felgate) #1

(^560) Chapter 14 A Brief Look at JavaScript
Let’s start by adding the code to validate the age. Edit the formvalidation.html file to
add the following script block in the section above the tag:



ThevalidateForm()function will check the age in the userAgeinput box. If it is less
than 18, the alert message will be displayed and a value of falsewill be returned and
the function will finish executing. The onsubmitevent handler will become "return
false"and the form will not be submitted. If the age is 18 or greater, the statements in
theifstructure will be skipped and the alert("Age is valid.");will execute. After
the user clicks the OK button in the alert message, the statement return true;will
execute and the onsubmitevent handler will become "return true"; thus, the form
will be submitted. Let’s test this out!
Type a value less than 18 in the userAgeinput box and click the submit button. If the
form submits right away, there is likely an error in the JavaScript code. If this happens,
open the Error Console and correct the errors indicated. Figure 14.19 shows the input
in the Age box and the alert message displayed after clicking the submit button.
Figure 14.19
The
validateform.html file
displayed in the
browser with input
for age less than
18—notice the alert
message
Free download pdf