JavaScript Alert, Confirm, and Prompt Dialogs


JavaScript provides built-in dialogs to interact with users through alerts, confirmations, and prompts. In this guide, we'll explore how to use these dialogs and provide examples to illustrate each type.


The Alert Dialog


The alert dialog displays a simple message to the user with an "OK" button:


<button class="button" onclick="showAlert()">Show Alert</button>
<script>
function showAlert() {
alert("This is an alert message.");
}
</script>

The Confirm Dialog


The confirm dialog prompts the user with a message and provides "OK" and "Cancel" buttons. It returns true if "OK" is pressed and false if "Cancel" is pressed:


<button class="button" onclick="showConfirm()">Show Confirm</button>
<script>
function showConfirm() {
const result = confirm("Do you want to proceed?");
if (result) {
alert("User chose 'OK'.");
} else {
alert("User chose 'Cancel'.");
}
}
</script>

The Prompt Dialog


The prompt dialog asks the user for input and returns the entered value. It can be useful for collecting data from the user:


<button class="button" onclick="showPrompt()">Show Prompt</button>
<script>
function showPrompt() {
const name = prompt("Please enter your name:", "John Doe");
if (name !== null) {
alert("Hello, " + name + "!");
} else {
alert("You canceled the prompt.");
}
}
</script>

Conclusion


JavaScript dialogs are handy for communicating with users and collecting input. The alert dialog is for simple messages, the confirm dialog is for user decisions, and the prompt dialog is for collecting input. Use them wisely to enhance user interactions in your web applications.


Happy coding!