How to stop the page from rendering the .cs
code on click of cancel button on javascript confirm box?
I have a button click event and in some IF
condition I am asking the user to confirm. Now when the user clicks on OK button, I have to bind the new data in a grid. but if the user clicks on cancel button, it should not refresh the grid with new data.
Question: On click of cancel button on JavaScript confirm box, how can I stop the following code to be executed, or how can I just return/break from JavaScript?
Can anyone please help me out with this? Thanks in advance.
Markup
<asp:Button ID="btnCopy" runat="server" Text="Copy" Enabled="false" OnClick="btnCopy_Click" ValidationGroup="Copy" />
Code
public void btnCopy_Click(object sender, EventArgs e) {
if (Convert.ToInt32(hidId.Value) > 0) {
string scriptString = "<script language='JavaScript'> ";
scriptString += "if (confirm('Are you sure to proceed?') == false) {return} ";
scriptString += "</script>";
Page.RegisterStartupScript("Confirm", scriptString);
BindDataGrid();
}
}
Confirm Box If the user clicks "Cancel", the box returns false.
The confirm() method is used to display a modal dialog with an optional message and two buttons, OK and Cancel. It returns true if the user clicks “OK”, and false otherwise. It prevents the user from accessing other parts of the page until the box is closed. message is the optional string to be displayed in the dialog.
Confirm box in JavaScript is used to take the permission from the user by clicking the Ok button or Cancel button. If we click Ok button then action will move to next step, if we click Cancel button then it will terminate the action there itself.
The confirm() method displays a dialog box with a message, an OK button, and a Cancel button. The confirm() method returns true if the user clicked "OK", otherwise false .
You are mixing server and client side code in the same event, it has to be separated:
Script:
function Confirm()
{
var record=confirm('Are you sure to proceed??');
if(record == 1)
{
return true;
}
else if(record == 0)
{
return false;
}
}
Markup:
<asp:Button ID="btnCopy" runat="server" Text="Copy" Enabled="false"
OnClick="btnCopy_Click" OnClientClick='return Confirm();' ValidationGroup="Copy" />
Code-behind:
public void btnCopy_Click(object sender, EventArgs e) {
if (Convert.ToInt32(hidId.Value) > 0) {
BindDataGrid();
}
}
You'll need to catch the response, for example:
if (window.confirm)
{
//handle the OK
}
else
{
//handle the cancel
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With