HTML and CSS Reference
In-Depth Information
EXAMPLE
11.13
<html>
<head><title>An HTML form and the "this" keyword and
Event Handler</title>
<script type="text/javascript">
1
function checkForm(
form1
){
2
if(
form1.your_name.value
== ""){
// Check for an empty string
3
alert("Please type in your name")
;
return(false);
}
else{
return(true);
}
}
</script>
</head>
<body><b>
4
<form method="post"
action="http://localhost/cgi-bin/check.pl"
onSubmit="return checkForm(this)
"><p>
<big><p>
Type your name here:
5
<input type="text" name="your_name"
size="50" />
<br /><br />
6
<input type="submit"
value="Submit" />
<input type="reset" value="Clear" />
</form>
</body>
</html>
EXPLANATION
1
The function called
checkForm()
is assigned to the
onSubmit
event. When the user
clicks the submit button, the event is triggered and as a result, the
checkForm
function is called. The
this
argument is a reference to this form. In
checkForm
, the
parameter is called
form1
, called on line 4 with the
this
keyword, which is a refer-
ence to the form.
2
When following the DOM hierarchy,
form1
refers to
document.forms[0]
. The text
field was named
your_name
on line 5. Now it can be referenced as
docu-
ment.form1.your_name. The value
property refers whatever was entered in the text
field. We are checking to see if the text field is the empty string, in which case we
will alert the user.
3
The user is alerted to enter his or her name in the text field.
4
The
onSubmit
handler sends one argument,
this
, to the function
checkForm()
. The
keyword
this
is a shorthand name for the current object; in this example the cur-
rent object is a form,
document.forms[0]
.