Quick Reach
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.
Experience this example online
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<button onclick=“showalert()”>Show javascript confirm</button>
<script type=“text/javascript”>
function showalert(){
var optsel = window.confirm(“Do you want to close window?”);
if (optsel == true){
alert(“You clicked OK!”);
}
else{
alert(“You clicked Cancel!”);
}
}
</script>
</body>
</html>
|
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<button onclick=“showalert()”>Show confirm</button>
<script type=“text/javascript”>
function showalert(){
var strname = “Mike”;
var optsel = window.confirm(“Hey “ + strname +“! nDo you want to close window?”);
if (optsel == true){
alert(“You clicked OK!”);
}
else{
alert(“You clicked Cancel!”);
}
}
</script>
</body>
</html>
|
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
Leave A Comment?