Press ESC to close

confirm JavaScript

0 1615

In this article we will talk about confirm in JavaScript, that is, how to create a window where the user can make a choice.

With the confirm () method, unlike the alert () method, communication is therefore not unilateral but bilateral.

confirm JavaScript – example 1

Let’s immediately take an example of use.

Try to enter some data in the fields below and then click on the Reset button. The window will appear that will tell you if you really want to reset the data.

Then, in any part of the web page, we insert the form with the labels, the text boxes and the reset button.

<form name="senda-data" onreset="return confirmation()">
  <input type="text" name="name">
  <input type="text" name="lastname">
  <input type="reset" value="Reset">

Note, in particular, that I have inserted the onreset event within the form tag.

After, as explained in the last lesson, we insert the following JavaScript code also in the same page for simplicity.

Inside the confirm method we then write if you want to reset the module.

function confirmation() {
  var reset = confirm("Do you want to reset the form?");
  return reset;

confirm JavaScript – example 2

Let’s take another very simple example of using the confirm () method, in which the window, after pressing the button, will display the choice we have made.

Try again to enter the data in the fields below and then press reset. The dialog box after pressing the button will tell you the choice you have made.

For the html we use the same form as before.

Ho modificato invece il codice JavaScript, per poter visualizzare, subito dopo, un alert che ci indica la scelta che abbiamo effettuato.

Usiamo un’istruzione condizionale, ovvero la funzione se … altrimenti, che controlla se il pulsante ok è stato premuto. Se è così useremo il metodo alert() per visualizzare che si è scelto di reimpostare i dati, altrimenti utilizzeremo sempre il metodo alert() per dire che si è scelto di premere annulla.

Ecco dunque l’esempio completo che utilizza JavaScript confirm:

function confirmation() {
  var reset = confirm("Do you want to reset the form?");
  if (reset === true){
       alert("You have chosen to reset your data!");
  else {
      alert("You hit Cancel!");


In order to develop this example, you can follow the lesson on conditional statements in JavaScript presented in this lesson: if else statement.

These are just simple examples of using the confirm method in JavaScript.

Some useful links

JavaScript tutorial

JavaScript Calculator

Object in JavaScript

For in loop

Caesar cipher decoder

Slot Machine in JavaScript

Introduction to JavaScript language

Learn JavaScript – basic concepts

Other stories

prompt JavaScript

Next Story

alert JavaScript

Previous Story