[thelist] Simple JavaScript question

Aylard JA (James) jaylard at equilon.com
Mon Aug 7 10:47:32 CDT 2000


Peter Small wrote:
> The function confirm() returns true if OK pressed. It returns false if
> cancel is pressed.
> 
> Wouldn't the return have to be included in an if... then... conditional -
> to direct the transfer to another URL only if true was returned by the
> confirm() function?

	You could do an if...then statement, but it is unnecessary. If you
did use one, it would look like this (keep in mind that the confirm() dialog
returns true when "OK" is clicked, and false when "Cancel" is clicked):

if (true == confirm("Are you sure?")) { 
  return true ;
}
else {
  return false ;
}

	The if statement could also be written:

if (confirm("Are you sure?")) { 
...

	But either way, you can see that this is a bit redundant; so, the
more efficient way is simply to return the value of the confirm() dialog,
whichever it is:

return confirm("Are you sure?") ;

	Also, keep in mind that you use the return statement in two separate
places for two separate purposes: once in the function, as shown above, to
return the result of the confirm dialog back to event handler; and the
second time in the event handler itself to determine whether the <a>
element's default onclick behavior (to navigate to a link) actually takes
place (if a value of true is returned, it does; if a value of false is
returned, it does not, leaving you at the current page).
	You could also forego the function altogether, as Eric's example
showed:

<a href="http://www.citycent.com" onClick="return confirm('are you
sure');">Click here</a>

	The drawback to this approach is that if you want to apply this same
confirm() method to every link, you'll create extra coding and a lot of
extra work if you decide you want to edit the whole thing later. As a
general rule, it is better to place such code within a function.
	One potentially big caveat to the approach that I have offered is
that it will not work in JavaScript 1.0 browsers (Netscape 2, IE3), but
instead will throw an error. The ability to return false to cancel an
onclick event's action was implemented in JavaScript 1.1.

hth,
James Aylard
jaylard at equilon.com




More information about the thelist mailing list