JavaScript Interaction: `alert()`, `prompt()` and `confirm()`
What is Interaction?
In JavaScript, interaction refers to the ability of a program to communicate with the user. It allows us to prompt the user for input, display messages, and confirm actions.
The alert() function
The `alert()` function is used to display an alert box with a specified message and an OK button. It is commonly used to display a message to the user or provide a notification. The alert box is modal, which means the user cannot interact with the rest of the web page until they close the alert box.
Here is an example of using the `alert()` function:
alert("Hello, World!");
When this code is executed, it will display an alert box with the message "Hello, World!" and an OK button.
The prompt() function
The `prompt()` function is used to display a dialog box that prompts the user for input. It takes two parameters: the message to display in the dialog box, and a default value(optional) for the input field.
The syntax: result = prompt(message to display, [default]);
Here is an example of using the `prompt()` function:
var name = prompt("Please enter your name:", "John Doe");
console.log("Hello, " + name + "!");
When this code is executed, it will display a dialog box with the message "Please enter your name:" and an input field. The default value for the input field is "John Doe". The value entered by the user will be stored in the `name` variable, and then it will be printed to the console.
The confirm() function
The `confirm()` function is used to display a dialog box with a specified message and OK/Cancel buttons. It is commonly used to ask the user to confirm an action. The `confirm()` function returns a boolean value indicating whether the user clicked OK or Cancel.
The syntax: result = confirm(question);
Here is an example of using the `confirm()` function:
var result = confirm("Do you want to delete this item?");
if (result) {
console.log("Item deleted.");
} else {
console.log("Item not deleted.");
}
When this code is executed, it will display a dialog box with the message "Do you want to delete this item?" and OK/Cancel buttons. If the user clicks OK, the `result` variable will be set to true. If the user clicks Cancel, the `result` variable will be set to false. Based on the value of `result`, a corresponding message will be printed to the console.
Key Takeaways
- The `alert()` function is used to display an alert box with a message.
- The `prompt()` function is used to display a dialog box that prompts the user for input.
- The `confirm()` function is used to display a dialog box that asks the user to confirm an action.
- The `prompt()` and `confirm()` functions return the value entered or selected by the user.
Comments
Post a Comment