Cathal Lenihan Cathal Lenihan - 3 years ago 49
C# Question

How to warn a user when leaving a page but not when pressing a button?

I want users to get a warning when they are leaving a webpage. I also want users to get a different alert when they press on a button for submitting something. At the moment when you leave the webpage everything works correctly but when you press submit you see both warning messages. How do I get this to just show the one alert?

<asp:Button Style="display: inline-block; margin-left: 120px; margin-top: 10px;" ID="SendEmail" runat="server" CssClass="btn-flat success" Text="Send email" OnClick="btnUpdate_click" Visible="true" Enabled="True" OnSubmit="window.onbeforeunload = false;" OnClientClick="if ( !confirm('Are you sure you want to send this email?')) return false;"/>
<script>

window.onbeforeunload = function () {
return "Do you want to leave this page?";
}


I use window.onbeforeunload for leaving the webpage and have OnClientClick called when you press on the button for submitting. I have no experience with Javascript so I am not sure what I am doing.

Answer Source

You can set a variable while clicking on submit. So when it's true do not show the window.onbeforeunload message.

Do somthing like this.

 <asp:Button Style="display: inline-block; margin-left: 120px; margin-top: 10px;" ID="SendEmail" runat="server" 
                CssClass="btn-flat success" Text="Send email" OnClick="btnUpdate_click" Visible="true" Enabled="True" 
                OnSubmit="window.onbeforeunload = false;" OnClientClick="return Confirm();" />

and JS

var IsSubmit = false;

function Confirm()
{
    IsSubmit = true;
    if ( !confirm('Are you sure you want to send this email?')) 
        return false;
}

if(IsSubmit != true)
{
    window.onbeforeunload = function () {
         return "Do you want to leave this page?";
   }
}

Thanks

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download