views:

343

answers:

2

How can I prevent onbeforeunload from being called when clicking the submit button?

$(document).ready(function() 
 {
  $('input:text,input:checkbox,input:radio,textarea,select').one('change', function() 
  {
   //('BODY').attr('onbeforeunload',"return 'Leaving this page will cause any unsaved data to be lost.';");
   if(
   window.onbeforeunload = function() { return 'You have unsaved changes!'; }

  });

 });
A: 

You can't prevent the calling of unbeforeunload, but using a global flag variable, you can control whether it displays a warning.

in the document, add the script:

warn_on_unload = "You have unsaved changes!"

in the submit event, add:

warn_on_unload = "";

the definition of the event, change to:

window.onbeforeunload = function() { return warn_on_unload; }

through warn_on_unload, you can now switch the warning message on or off at will.

Pekka
It tried and it worked! Thanks.
ASD
How to add blur, keypress in this $('input:text,input:checkbox,input:radio,textarea,select').one('change', function()
ASD
It's a different issue, you best open a new question for that.
Pekka
A: 

Here is the final code: $(document).ready(function() {

    var warn_on_unload="";
    $('input:text,input:checkbox,input:radio,textarea,select').one('change', function() 
    {
         warn_on_unload = "Leaving this page will cause any unsaved data to be lost.";

        $('#submit').click(function(e) { 
         warn_on_unload = "";});    
        window.onbeforeunload = function() { return warn_on_unload; }

    });

});
ASD