In my previous tutorials, I’d explained how to show confirm message box from code-behind, how to call javascript function from code-behind, how to show alert message in asp.net and more cracking tutorials on Asp.net, JavaScript, jQuery here.
Now here in this tutorial, I’ll explain how you can show confirm message box in javascript from client-side in asp.net with example code-snippet.
The confirm() method displays a dialog box with a specified message written under method. When you call the method it will show alert message that specified in method along with an Ok and a Cancel button. The confirm() method returns true if the user clicked “Ok”, and false otherwise.
A confirm box is often used if you want the user to verify or accept something such as want to ask before deleting records, agree with terms and conditions and so on. You can show confirm box into two ways using javascript. I’ll show you both methods with example in this tutorial.
Method1 – Confirm Message Box In JavaScript Function
I recommend you to use this method when you want to perform some task when user click on “Ok” or “Cancel”, otherwise just for confirmation use Method2, that is described below. To use Method1, first add the following JavaScript function in head section, like this:
function CallConfirmBox() {
if (confirm(“Are you sure you want to delete record?”)) {
//OK – Do your stuff or call any callback method here..
alert(“You pressed OK!”);
} else {
//CANCEL – Do your stuff or call any callback method here..
alert(“You pressed Cancel!”);
}
}
</script>
Then call that function on asp.net button click event like OnClientClick=”CallConfirmBox();” as below:
Here is the complete HTML Markup code that I used for this demonstration to confirm message box in javascript for my .aspx page:
<head id=”Head1″ runat=”server”>
<title>Confirm Message Box in JavaScript Example in Asp.net</title>
<script type=”text/javascript”>
function CallConfirmBox() {
if (confirm(“Are you sure you want to delete record?”)) {
//OK – Do your stuff or call any callback method here..
alert(“You pressed OK!”);
} else {
//CANCEL – Do your stuff or call any callback method here..
alert(“You pressed Cancel!”);
}
}
</script>
</head>
<body>
<form id=”form1″ runat=”server”>
<h4>Confirm Message Box Example using JavaScript in Asp.net</h4>
<div>
<asp:Button ID=”btnCall” runat=”server” Text=”Click Me!” OnClientClick=”CallConfirmBox();” />
</div>
</form>
</body>
</html>
Method2 – Confirm Message Box In JavaScript Using OnClientClick Event
I recommend you to use this inline method when you just want to confirm user, for example you want to confirm user before deleting or updating records. I already used this method in my previous tutorials while deleting records, to see example check insert update delete gridview data example and gridview inline insert update delete data example here.
Here is the sample code to ask confirm message box inline OnClientClick event:
runat=”server” Text=”Click Me!” />