JavaScript's confirm() Method and Forms: WebReference.com | WebReference

JavaScript's confirm() Method and Forms: WebReference.com


Using JavaScript's confirm() Method to Control Form Submission

by Stephen F. Mai

A Friendlier Way to Interact

Many developers aren't aware of JavaScript's ability to make a form truly interactive. Some place the burden of form-field validation and user interaction on the server, requiring a long 'round-trip' from the browser to the server and back again to the browser in order to complete the interaction.

However, the JavaScript confirm() method allows a user to cancel the submission of a form, based on an interactive alert from the browser. If the user decides not to submit the form, he or she can cancel the submission before the browser ever sends it across the network. In addition, this alert can even display the information that the user entered into the form to verify that it is correct. And the best part about it is that it's cross-browser and cross-platform compatible.

Submission Hold

Before we can examine how to give the user the ability to cancel a form's submission, we must first review how JavaScript controls the submission of a form. In order to do this, we implement the onSubmit event-handler to call a JavaScript function and then look at the return value of the function called by that event-handler.

In the following example, the form cannot be submitted unless the user enters something in the 'name' field. Although this is a very simple example, it illustrates JavaScript's ability to prevent a form from being submitted, based on the return value of a function. Notice that we must have the keyword 'return' before the name of the function that we're calling in the onSubmit event handler; this is the secret to stopping the form's submission.


<HTML>
<HEAD>
<TITLE>Form Submission Test</TITLE>
<SCRIPT LANGUAGE=JAVASCRIPT>
function verify(){
    if(document.forms[0].myName.value==""){
        alert("Please enter a name in the field");
        return false;
        }else{
        return true;
        }
  }
</SCRIPT>
</HEAD>
<BODY>
<!--Note the word 'return' in our event handler.
    That makes the submission of the form dependent upon
    the return value of the function called. -->
    <FORM ACTION="http://www.webreference.com" onSubmit="return verify()">
        Name: <INPUT TYPE=TEXT NAME="myName" size=30><BR>
              <INPUT TYPE=SUBMIT VALUE="Submit">
   </FORM>
</BODY>
</HTML>

See the Example

Page Two: Is That Your Final Answer?

http://www.internet.com

Comments are welcome
Written by Steve Mai and

Revised: December 7, 2000

URL: http://webreference.com/programming/javascript/confirm/