Confirm Method and the Return Keyword

Go to the home page.

A JavaScript confirmation dialog box looks similar to an alert box, and allows the scripter to define the text that appears on it. The confirmation box differs by offering two options for the user to press - OK and Cancel. These options essentially allow a user to confirm or reject a question defined by you.

Since the user has two possible answers to choose from, be sure to word your question so that an "OK" or "Cancel" will be a logical answer. If that is not possible, include instructions as to how each of those answers will be interpreted.

Being able to prompt a yes or no from the user is neat, but it is completely useless if we aren't able to follow through with specific scripting based on which answer they chose. Lucky for us, the confirm method automatically returns a value of true or false (true if the user presses OK and false if the user presses cancel).

By setting a variable equal to a confirm method invocation, your script can test that variable for a true or false value (boolean value) to find out what the user chose, or return that value for use in another location.

Remember - the two rules for using the return keyword are:
1. If the return keyword is used in a function body, a value is returned (or sent) back to where function is called.
2. If the return keyword is used in an event handler, a value is returned (or sent) to the browser.

The beg() function in this example is invoked when the user clicks on a link that will take them to another page. The function generates a confirmation dialog box that confirms whether or not the user really wants to leave. If the user choses "OK", they go to another page, if they chose "Cancel" they will remain on this page.

The first statement in the function beg() creates a variable to hold the value that will be returned by the confirm method. The second statement returns that variable to another location. By returning the variable assigned to the confirm method, we are actually returning the answer the user chose. Simple enough, but why and where is that value returned to?

function beg() {
var myConfirm = confirm("Sure you want to leave?");
return myConfirm
The value of the myConfirm variable is returned to the place the function is invoked - in this case, the onclick event handler located in the <a> tag. Since the returned value will be either true or false, we can use that value along with the return keyword again for a separate command we will send the browser.

<a href="" onClick="return beg()">Go to the home page</a>
By preceding the function call with the return keyword, that statement is interpreted as "return true" or "return false". Since the return keyword is used within an event handler, the value is returned to the browser, telling it whether or not to open the URL.


View Source | Home | Contact