HTML and CSS Reference
In-Depth Information
13.6.6 Forms and the onSubmit Event Handler
When you submit an online order for a purchase you made at a Web site like Amazon
or iTunes, once you have submitted the order, you can't back out. It's too late. You have
your e-mail confirmation before you can blink an eye, your new tune or movie ready
to play, and your payment has already been processed. You pressed the submit button,
maybe with a different label, like “Order now,” but pressing that button triggered an
event that caused your order to be processed.
The onSubmit event handler was discussed in detail in Chapter 11, but it is included
again in this chapter because it is such an important form event. You will see this event
again in Chapter 17. If you recall, the onSubmit event is an attribute of the HTML <form>
tag and is triggered when the user presses the submit button after filling out a form. This
event allows the programmer to validate the form before sending it off to the server. If the
return value from the event handler is true, the form will be submitted; if false it won't be
submitted. The following examples demonstrate two different programs using an onSubmit
event handler. Example 13.17 creates two text fields for the user's name and address. The
onSubmit event handler is triggered when the user clicks the submit button, causing a
function to be called that will produce a little popup window with the user's input data. By
allowing the user to view the data entered, the submission can be delayed for further vali-
dation, and so on. Example 13.18 is a snippet of code that could be used after a shopping
cart has been filled and the user is ready to go to the checkout page. When the user clicks
the submit button labeled “Go to Checkout” a function will be called. It returns true if the
user has checked a checkbox and false if he or she hasn't. By checking the small checkbox,
the user is confirming that he or she is ready to submit the form data. Then a server side
program will perform further validations and calculations, send e-mail, open a database,
and so on. Both of the examples show the value of having an onSubmit handler to catch
the form before it is submitted to allow the user to change a field, go back to another page,
confirm that he or she has finished and is ready to order, and so on.
EXAMPLE 13.17
<html>
<head><title>The onSubmit Event Handler</title>
<script type="text/javascript">
1
function popUp(){
2
newWin=window.open ('','NewWin','toolbar=no,
status=no,width=500,height=200');
3
newWin.document.write ("<body bgcolor='yellow'>
<h3>Form data</h3>");
newWin.document.write("<b>Your name is:</b> " +
document["form1"].namestring.value);
newWin.document.write ("<br /><b>Your address is:
</b></body>" + document["form1"].address.value );
newWin.document.close();
}
</script>
Continues
 
 
Search WWH ::




Custom Search