Contents
JavaScript confirm: Main Tips
- The JavaScript
confirm()
method displays a specified message in a dialog box, containing OK and CANCEL buttons. - A confirm box is used to accept or verify something.
- The confirm JavaScript box forces the browser to read the message. By doing so, it takes the focus off the current window. This function should not be overused, as it restricts the user from reaching other page parts until the box is closed.
- The
confirm()
method returns true when users click OK, and false when they click CANCEL or X.
confirm() Explained
This function displays a message in a dialog box. Nowadays, website owners are always aiming to make their pages user-friendly. One of the possible usages of JavaScript confirm()
function is to display a confirm message for deletion.
Let's say a person wants to delete a photo from a website. Since accidents happen and the delete button might have been pressed on the wrong image unintentionally, the website displays a confirm message to check this decision.
Such a JavaScript confirm delete function can be achieved with the confirm function. The command would be written like this:
confirm("Delete this item?");
Please note that even though JavaScript confirm delete function is a handy feature, not all visitors might appreciate it. Until the displayed message is closed, visitors won't be allowed to access the rest of the page.
Nevertheless, this is only one common example, illustrating the possible usages of JavaScript confirm function. Other examples could ask to verify many actions. For example, we could have a confirm JavaScript box written like this:
Standard Syntax
The set rules for writing JavaScript confirm method should not scare you away from using it. After looking at the basic syntax of this function, you will realize there is not much to remember:
confirm(message)
As you can see, the method can have one argument, but even that is not required. The message
argument defines the exact text to be displayed in the confirm box.
Even though it is not obligatory, we usually state it to customize the dialog box and make it more attractive. Nevertheless, the choice is yours: you do not have to specify this parameter if you don't find it necessary.
Using Javascript confirm()
This example illustrates the output the users get after they interact with the confirmation box. You can see that if they click OK, the response will be treated as true. When you click CANCEL, the response will be treated as false:
var text;
var z = confirm("Press this confirm button!");
if (z == true) {
text = "Confirm is pressed!";
} else {
text = "Cancel is pressed!";
}
In case the confirm message looks clumsy, it is possible to insert a line-break to display the message in several lines. Line-breaks can be achieved by adding \n
in the place that you want the text to be moved to another line.
The example below shows how you should add \n
to your code: