Add to Favorites

javascript, confirm before you go

Sometimes you may want to have a user acknowledge an action and have a second thought about exactly what they are doing before carrying out their request. Javascript fits pretty well for most of these situations. There is a nifty function in javascript named confirm(). This little function takes one argument ( a message for the user ), and presents an alert box to the user showing the message along with an "Ok" and "Cancel" button. If the user clicks ok, confirm returns true, if they click cancel or close the dialog it returns false. You can use this in a combination of ways to confirm actions such as form submission or links.

For example, if you wanted to make a function you could use to confirm a user wants to go to a link when they click it. You could create a simple function such as

function confirmGo(m,u) {
if ( confirm(m) ) {
window.location = u;
}
}

You could use it in your anchor

<a href="javascript:confirmGo('Are you sure you want to go to google?','http://www.google.com')">go to google</a>

When the users click this link, they will be asked if they are sure, if they click cancel they will go no where, but if they click go then they will be sent to the url.

Comments

02/02/2010 8:33am
you can place your function in a global js file for your site as well, it's useful in many places

Leave a comment

To leave a comment, please log in / sign up