ArticleZip > Make Javascript Alert Yes No Instead Of Ok Cancel

Make Javascript Alert Yes No Instead Of Ok Cancel

When it comes to creating user-friendly interfaces on the web, the JavaScript alert function is a handy tool for displaying important messages to users. By default, the alert function presents users with a simple dialog box containing an "OK" button, which they can click to dismiss the alert. However, in certain situations, you may want to provide users with a choice between "Yes" and "No" options rather than a single "OK" button.

To achieve this functionality, you can utilize the JavaScript confirm function instead of the alert function. The confirm function creates a dialog box with "OK" and "Cancel" buttons by default, but with a few simple tweaks to the code, you can customize the button labels to display "Yes" and "No" instead.

To implement the "Yes" and "No" buttons in a JavaScript confirmation dialog, follow these steps:

1. Declare a variable to store the return value of the confirm function. This return value will be true if the user clicks "OK" (which will be equivalent to "Yes" in our case) and false if the user clicks "Cancel" (which will be equivalent to "No").

Javascript

var userResponse = confirm("Do you want to proceed?");

2. To change the button labels from "OK" and "Cancel" to "Yes" and "No," you need to create a custom confirmation dialog using the confirm function along with some conditional logic. Here's an example of how you can achieve this:

Javascript

var userResponse = confirm("Do you want to proceed?");
if (userResponse) {
    alert("User clicked Yes!");
} else {
    alert("User clicked No!");
}

3. Another approach to customizing the confirmation dialog buttons is to create a custom dialog box using HTML, CSS, and JavaScript. This method provides more flexibility in designing the dialog box according to your requirements. You can create a modal dialog with "Yes" and "No" buttons styled to match your website's design. Here's a simplified example of how you can implement a custom dialog box:

Html

<div id="customDialog">
    <p>Do you want to proceed?</p>
    <button id="yesButton">Yes</button>
    <button id="noButton">No</button>
</div>

document.getElementById('yesButton').addEventListener('click', function() {
    alert("User clicked Yes!");
});
document.getElementById('noButton').addEventListener('click', function() {
    alert("User clicked No!");
});

With these techniques, you can enhance user interaction on your website by providing them with a choice between "Yes" and "No" buttons in JavaScript confirmation dialogs. Experiment with customizing the dialog box further to create a seamless and intuitive user experience.