Click here to Skip to main content
15,918,742 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a .net web form written in C#. To warn users that they may have unsaved data, this script was included.

JavaScript
<script type="text/javascript">
	<!--
    
    var warnMessage = "You have entered new data on this page.  If you navigate away from this page without first saving your data, the changes will not be saved. To save your data, click the Cancel button, then save your data before leaving this page.";
   
    var g_isPostBack = false;
    
    function windowOnBeforeUnload() {
        if (g_isPostBack == true)
            return; // Let the page unload

        if (window.event)
            window.event.returnValue = warnMessage; // IE
        else
            return warnMessage; // FX
    }

    window.onbeforeunload = windowOnBeforeUnload;	
    
   //->
</script>


The script works great, except its supposed to not fire when the Submit button is clicked. What happend is g_isPostBack is set to false instead. Any ideas on how to turn off the postback for the submit button would be great.
Posted
Updated 3-Jan-12 10:58am
v2

i believe a simple javascript function call on onclick event of submit call that sets the g_isPostBack to true will do the needful.

further there are more customized jquery plugins available like

Dirty Forms[^]
 
Share this answer
 
Comments
twhaight 12-Jan-12 10:32am    
That was something I already tried. I created a function called setPostback
Collapse | Copy Code

function setPostBack() {
g_isPostBack = true;
}

Next I added this line to the button (called btnSubmit):
Collapse | Copy Code

btnSubmit.Attributes.Add("onclick", "return setPostBack();");

To see what happens with the objects, I installed Firefly to my browser. When the form is submitted, a postback still occurs, and the variable is reset to false.
I did 2 things to make the warnings work.
1) I changed the warning script to this
JavaScript
<script type="text/javascript">
	<!--   
    var warnMessage = "You have entered new data on this page.  If you navigate away from this page without first saving your data, the changes will not be saved. To save your data, click the Cancel button, then save your data before leaving this page.";
      
    var g_isPostBack = false;

    function windowOnBeforeUnload() {
        if (g_isPostBack == true)
            return; // Let the page unload

        if (window.event)
            window.event.returnValue = warnMessage; // IE
        else
            return warnMessage; // FX
    }


2) I added a updatepanel to the page.

XML
0 points awarded.
    window.onbeforeunload = windowOnBeforeUnload;
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900