Sometime, it is desired to raise an Alert or get confirmation on inputs or to have a kind of input from the users. To do such things on web pages, JavaScript provides mainly three types of pop-up or dialog boxes. These are:
Alert box gives only one button "OK” and it is mandatorily be clicked to close the Alert popup box. It may be used to display some instructions or to display warning type of messages. An alert box is often used if you want to make sure information comes through to the user. When an alert box pops up, the user will have to click "OK" to proceed.
Syntax:
alert(“message to be displayed”);
Or:
windows.alert(“message to be displayed”);
For example, if mobile no field requires entering only numbers but the user does not provide any input or enter text data, then as a part of validation, an alert box may be used to display a warning message.
Examples:
Output:
If it is desired from the user to verify or accept something, a confirmation dialog box is used. A confirm box, there are two options to choose from, i.e. click "OK" or "Cancel" to proceed. If the "OK" is clicked, the box returns true and if the "Cancel", the box returns false.
Syntax:
confirm(“Verification message to be displayed”);
Or:
windows.confirm(“Verification message to be displayed”);
For example, if mobile no field requires entering only numbers but the user does not provide any input or enter text data, then as a part of validation, an alert box may be used to display a warning message.
Examples
Output:
The prompt dialog box may be used if we want to pop-up a text box to get user input, i.e. a prompt box may be used if we want the user to input a value before entering a page. Thus, it enables you to interact with the user.
The prompt dialog box has two buttons: OK and Cancel and the user have to click either "OK" or "Cancel" to proceed after entering an input value. If the user clicks the OK button, the window method prompt() will return the entered value from the text box. If the user clicks the Cancel button, the window method prompt() returns null.
Syntax:
prompt("Label","defaultText");
Or:
window.prompt("Label","defaultText");
Here, Label is the label of the displayed text box. defaultText is the string to display in the text box by default. In this Text box, user may need to enter the input text.
Examples
Output:
These Popup Boxes can be used along with functions etc in the JavaScript Program to accept user inputs and display customized messages as per requirements.
Consider the following example:
Example:
Examples
Click on the button to enter your marks:
Output: On loading the page.
Output: On clicking the “Enter your Name” button and entering the name
Output: After Clicking the button