Question

I tried to use jQuery serialize to confirm user for form content change. It seems working. The issue is that before I submit the form, I reset the window.onbeforeload to null and hope it will not popup the confirmation dialog when user clicks submit button. But my code below still show the popup when submit button clicked.

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery warn page leaving</title>
<link rel="stylesheet" href="../jquery-ui-1.10.4.custom/css/smoothness/jquery-ui-1.10.4.custom.css">
<script src="../jquery-ui-1.10.4.custom/js/jquery-1.10.2.js"></script>
<script src="../jquery-ui-1.10.4.custom/js/jquery-ui-1.10.4.custom.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script>
$(document).ready(function(){
$('#form').data('serialize',$('#form').serialize());
}
  );

$(window).bind('beforeunload', function(e){
   if($('#form').serialize()!=$('#form').data('serialize'))
      return "Data changed.";
   else e=null;
   // i.e; if form state change show box not.
});

$("#form").submit( function() {
    alert("called submit");
    window.onbeforeunload = null;
 });

 function disableBeforeUnload() {
  alert ("call disable func");
  window.onbeforeunload = null;
}
 </script>
</head>
<body>
<a href="http://www.google.com">Go to google</a>

<form id="form" name='experiment' action="#" onsubmit="disableBeforeUnload();">
<Label for='firstName'>First name: </label><input name = 'fname' type="text" size="30" />

<Label for='firstName'>Last name: </label><input name = 'lname' type="text" size="30" />
<select name ='options'>
<option value=1> One</option>
<option value=2> two</option>
 <option value=3> three</option>
 </select>
 <button type="submit" name="submit" />
 </form>

 </body>
 </html>

No correct solution

OTHER TIPS

Maybe it'll be better to use unbind function? Like following:

$("#form").submit( function() {
  alert("called submit");
  window.unbind('beforeunload')
});

You need to unbind the jQuery handler, not the native onbeforeunload event. So use:

$(window).unbind('beforeunload');

Or now, preferred method is to use off() to unbind:

$(window).off('beforeunload');

And on() for binding instead of bind(). Be aware though that bind() and unbind() aren't deprecated, it's still ok to use it.

jsFiddle

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top