Using feedback from confirm in JavaScript

In JavaScript we normally use the method prompt() to get feedback from a user, but if the feedback we actual want is just a yes or a no, it might be easier to just implement a confirm() method instead. The confirm() method has two buttons, an OK and a cancel button. When pressing OK JavaScript returns a boolean true. If however we click on cancel or on the X, JavaScript returns a boolean false.

Knowing this outcome we can implement a dual action based on the user’s click. Take for example the following simple script:

var z = confirm("Would you like to dance?");
if(z === true){
console.log("Thanks, let's dance!");
} else {
console.log("No? Will it be ok if I ask again some other time?");
}

On line 1 the confirm action is assigned to some variable hereby named y. The reason to assign the outcome to a variable is because of inconsistencies with different browsers. By assigning confirm to a variable we use the variable value instead of the direct feedback from confirm. It is a safer implementation.

Hope it comes handy!

Tony de Araujo
Tech Writer

Advertisements

Author: tarau

technical writer, web technologies

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s