Java Reference
In-Depth Information
Enter an invalid value into the age text box, such as aaaa , and when you try to leave the box, it'll tell
you of the error and send you back to correct it.
Finally, click the Check Details button and both text boxes will be checked to see that you have
completed them. If either is empty, you'll get a message telling you to complete the whole form, and it'll
send you back to the box that's empty.
If everything is filled in correctly, you'll get a message thanking you, as shown in Figure 11-5.
Within the body of the page, you create the HTML elements that define your form. Inside your
form, which is called form1 , you create three form elements with the names txtName , txtAge , and
btnCheckForm :
<form action="" name="form1">
Please enter the following details:
<p>
Name:
<input type="text" name="txtName" />
</p>
<p>
Age:
<input type="text" name="txtAge" size="3" maxlength="3" />
</p>
<p>
<input type="button" value="Check details"
name="btnCheckForm">
</p>
</form>
You'll see that for the second text box (the txtAge text box), you have included the size and
maxlength attributes inside the <input/> element. Setting the size attribute to 3 gives the user an idea
of how much text you are expecting, and setting the maxlength attribute to 3 helps ensure that you
don't get overly large numbers entered for the age value.
You register listeners for various events on these elements:
var myForm = document.form1;
myForm.txtName.addEventListener("change", txtNameChange);
myForm.txtAge.addEventListener("blur", txtAgeBlur);
myForm.btnCheckForm.addEventListener("click", btnCheckFormClick);
The first text box's change event is handled by the txtNameChange() , the second text box's blur event
is handled by txtAgeBlur() , and the button's click event will cause btnCheckFormClick() to execute.
Let's look at each of these functions in turn, starting with btnCheckFormClick() .
The first thing you do is define two variables, txtName and txtAge , and set them to reference
<input/> elements with the same names:
function btnCheckFormClick(e) {
var txtName = myForm.txtName;
var txtAge = myForm.txtAge;
Search WWH ::




Custom Search