i2tutorials

JavaScript Confirm

 

In JavaScript, the confirm method invokes a function that prompts the user for confirmation of a particular action. Confirm () invokes a dialogue with a question and two options, OK and Cancel, using a window object. By selecting the OK option, the function will be executed; by selecting the Cancel option, the block code will be aborted.

It returns true if the user selects the OK option; otherwise, it returns false.

Syntax:

confirm("Select an Option!");  

Parameters:

A “message” value in string format is required to display in the confirmation dialog box.

Return value:

If the OK option is selected, the confirm method returns a Boolean output, either true or false.

The boolean value indicates whether OK (true) or Cancel (false) was selected. The returned value is always false if a browser ignores in-page dialogues.

Usage of the Confirm method

Example

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p>Click the button to invoke the confirm().</p>
<button onclick="myFunction()">Click Here</button>
<p id="conf"></p>
<script>
function myFunction() {
var result;
var r = confirm("Select an Action!");
if (r == true) {
result = "You have select The OK!";
} else {
result = "You have select The Cancelled!";
}
document.getElementById("conf").innerHTML = result;
}
</script>
</body>
</html>

OUTPUT : 

As shown in the above html page, some text and an action button will be displayed as follows:

Clicking the Click Here button will display a dialogue box with the specified message as well as options for OK and Cancel.

If we select the OK action, the code true block code will be executed; otherwise, the false block code will be executed. Take a look at the following output:

 

Exit mobile version