Friday, 20 February 2009


How to Use the Javascript Confirm Function


from wikiHow - The How to Manual That You Can Edit

Have you ever needed to make the user confirm something? Ever wanted the user to click OK and be redirected to a site and click Cancel to stay on the current page? Read on and find out a very simple way to do so with the JavaScript confirm(); function.

Steps



  1. Create a variable and initialize its value to the return value of the confirm() function.
    var userChoice = confirm("Do you want to leave WikiHow?");
  2. Use a set of if statements or conditional operators to determine the effect of clicking OK or Cancel. When the user clicks OK, confirm() returns the value true. If
    userChoice ? (alert("Aw, bye!");window.location="http://www.google.com/") :
    alert("Alright! Thanks for sticking around.");


Tips


  • The confirm() function can be used directly within HTML as an event. For example:
    or If the user clicks Ok, the event will go forward, if not, it won't. It's that simple.
  • Using conditional operators is faster than using if statements, but it may look confusing.
  • You can use the confirm() function for anything including preventing underage users from entering your site.