Refinance now before rates go up! Get multiple rate quotes at GetMyLender.com.

Difference Between Javascript alert prompt and confirm methods

It is one of the most common questions asking while interview i.e. What are the different mechanisms of communicating with the user using dialog boxes ? The javascript window object uses dialog boxes to interact with the user. The dialog boxes are created with three methods:

• alert()
• prompt()
• confirm()

alert() dialog

The alert() dialog box is used to communicate with the user most probably for warnings of missed actions or on errors. For example, if the user not entered first name then you can use this alert() message to warn the user about it. Many developers used this method for debugging purpose but it is the wrong to used alert() for this.

            alert("Invalid First Name. Please enter valid first name."); 

The alert() method creates a new pop-up window (dialog box) which contains the user message and one OK button. Its look is depending upon browser which we used. So don’t bother about look. This is a modal window so all execution is stopped until the user clicks the OK button in the pop-up box.

It is not possible to change title of dialog box, still you want to change then you have to use third party scripts or create your own alert box.


prompt() dialog

The prompt() method asks the user for some inputs such as a any number, first name, email id, password etc.

            prompt("Please Enter Your First Name.", "First Name"); 

The prompt dialog box pops up with a simple message and text box with an OK button and a Cancel button. After the user enters text into the prompt dialog box, its value is returned (or null in case the user hit cancel). The prompt method takes in 2 arguments – the prompt message and a default value. The default value is optional and if provided is filled in the text box and is selected by default.

Suppose we passed name as Hemu then we will get that name by following code

            var fName = prompt("Please Enter Your First Name.", "First Name"); 

confirm() dialog

By using confirm dialog box we can ask some questions to the user. This method takes only one argument, the question you will ask the user. A question mark will appear in the box with an OK button and a Cancel button. If the user clicks OK button then it return true otherwise false. This is also a modal dialog - the user must agree before the action is completed.

            if (confirm("Are you sure you want to delete selected records?")) {
                      alert("Deleting Records...");
                  }
                  else {
                     alert("Your Record is safe in database");
                  }

I think you enjoyed to learn alert(), prompt() and confirm() methods.

No comments:

Post a Comment