JavaScript Alert and Confirmation Boxes

An alert box is a small dialog box that provides a user with important information. The most common uses are to inform ("alert box") the user about errors (e.g., especially with form validation), to provide simple help messages, or to require confirmation ("confirmation box") before allowing certain website actions. You’ll often see the confirmation box used before the applications performs a task that cannot be easily reversed, for example charging a credit card or deleting content.

The alert box relies on the JavaScript onClick event handler. Below is a simple alert box script:

<a href='javascript:onClick=alert("put webmaster's alert\n text here")'>Alert Me</a>

Note the use of ' and \n – a forward slash is used before all special characters and the n tells the alert box to insert a carriage return (line break).

Notice that we put the JavaScript code in the href field since the only point of an alert box is to inform. A confirmation box, on the other hand, is designed to take an action if someone responds affirmatively, specifically to visit a URL found in the href field. Below is a simple confirmation box script:

<a href="http://www.linkhere.com" onClick="javascript:return confirm('put your confirmation\n text here')">Confirm Me</a>

In this case, a "no" (cancel) answer does nothing, but a "yes" (OK) reply takes you to the URL specified.

Note that instead of putting including the confirmation text directly, you could instead implement a JavaScript function:

<a href="http://www.linkhere.com" onClick="return myjsfunction();)">Confirm Me</a>

Personally, I use both of these regularly, especially the confirmation box on my administrative pages that offer a delete option – it has prevented me from accidentally deleting database records on numerous occasions!

Like this content? Why not share it?
Share on FacebookTweet about this on TwitterShare on LinkedInBuffer this pagePin on PinterestShare on Redditshare on TumblrShare on StumbleUpon

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.