| by Arround The Web | No comments

How to Alert Yes No With the confirm() Function in JavaScript

Developers often need to get input from the users to decide further course of action. This input can be of many types, simplest of which is a yes or no answer. JavaScript provides us with inbuilt functionality which can be used to get simple yes/no answers from users. These simple, straight forward answers are often needed when the user is performing a sensitive task like deleting their profile. An example of such input would be the prompt by Facebook when you try to leave the webpage after writing an incomplete post. This simple user input reduces the chance of mistakes and makes sure that the user has clear intentions of performing the task.

Confirm() method

JavaScript offers the inbuilt confirm method to prompt the user with a message and get a Yes or No answer in response. The dialog box offers users with two options: Ok and Cancel. If the user presses Ok then the confirm() method returns true else it returns false. The syntax of confirm() method is really straightforward. Just invoke the window object and call the confirm() method:

window.confirm(text);

As the window object has global scope, its methods can be called without reference to the window object.

confirm(text);

The confirm() method takes a single optional argument which is the text that would be displayed on the dialog box. As stated above the confirm() method also returns a true or false value.

Using the confirm() method

You can simply call the confirm() method with an optional string to prompt the user for a Yes or No answer:

confirm("Do you want to proceed?");

You should store the value returned by the confirm() method inside a variable so it can be used later

let user_input = confirm("Do you want to proceed?");

It is important to note that the confirm() method is synchronous which means that all other JavaScript processes will be stopped and the user won’t be able to access any other parts of the webpage until they have provided an input. This can sometimes cause problems as developers do not want to restrict user’s access to web pages. The confirm() method also has another disadvantage that its dialog box’s position, style and options cannot be customised.

Conclusion

In this write-up we took an insight into the JavaScript confirm() method. The confirm() method is a convenient way of getting simple straight forward answers from users and can often come in handy. However, it has a few drawbacks because of which it should not be overused.

Share Button

Source: linuxhint.com

Leave a Reply