2 Demos of JavaScript Confirm Alert

The confirm alert

The confirm alert is the way to interact with visitors of your website by giving Ok and Cancel options to proceed. In the alert chapter, we saw how a user is given the single option (OK) to proceed.

See a confirm alert example

Confirm JavaScript dialog is useful in scenarios like a user is closing the browser window and you can ask him/her: “Are you sure you want to exit?”.

Similarly, as filling a form and user is in between the process of filling it and try to access some other link or quitting the site, you may ask “Are you sure you want to leave this form without completing it?” etc.

How to create JS confirm alert?

The syntax to use confirm function is:

confirm(“Message here”);

Or you can also use in that way:

window.confirm(“Do you want to close window?”);

The confirm dialog example

Following is a simple example of using the confirm dialog. As you click the button “Show JavaScript confirm” it will show confirm dialog box. Click the link or image below to see it online.

javascript confirm alert

Experience this example online

A confirm dialog example with variable

In this example, we will use a variable value in the JavaScript confirm alert. As you click on the button, the JS confirm will show up with the name taken from a variable. See example by clicking the link below:

Experience this example online

As you can see in above example, the name is taken from the variable, that you can also get from user input or it can be database driven etc. Also, we used “n” to add a new line in confirm box type.

Further Reading: JavaScript alert | JavaScript prompt dialog

Was this article helpful?

Related Articles

Leave A Comment?