views:

39

answers:

2

having issues with onbeforeunload. I have a long form broken into segments via a jquery wizard plug in. I need to pop a confirm dialog if you hit back, refresh, close etc on any step but need it to NOT POP the confirm dialog on click of the submit button. had it working, or at least I thought, it doesn't now.

<script type="text/javascript">
var okToSubmit = false;
window.onbeforeunload = function() {
document.getElementById('Register').onclick = function() { okToSubmit = true; };
if(!okToSubmit) return "Using the browsers back button will cause you to lose all     form data. Please use the Next and Back buttons on the form"; 
};
</script>

'Register' is the submit button ID. Please help!

A: 

The problem is that the onclick event handler will not be called prior to if(!okToSubmit). All you are doing when you say:

document.getElementById('Register').onclick = function() { okToSubmit = true; };

Is just setting up the event handler. You are not actually retrieving the value of okToSubmit.

One way to fix this might be to setup the onclick event handler before registering onbeforeunload.

Justin Ethier
How, simply moving it up a line made the whole thing not work...
Dirty Bird Design
You need to wait for the DOM to load before you call any of this code. You can use `document.onload` for this purpose.
Justin Ethier
A: 

Plain old JS syntax a little rusty, so here it is in jQuery if anyone ever needs it, this works, at least for a form submit button. Change method to get if it suits your needs

<script type="text/javascript">
$(document).ready(function(){
  var action_is_post = false;
  $("form").submit(function () {
    action_is_post = true;
  });

  window.onbeforeunload = confirmExit;
  function confirmExit()
  {
    if (!action_is_post)
      return 'Using the browsers back, refresh or close button will cause you to lose all form data. Please use the Next and Back buttons on the form.';
  }
});

</script>
Dirty Bird Design