views:

62

answers:

2

I have a web form on my web page. Before the user leaves the page, I want a javascript popup message asking the user if they have completed the form with a "Yes" or "No" button on it. If the user clicks "Yes", then they are brought to the page they intended to go to. However, if the user clicks "No", then the user remains on this page.

I am not very familiar with Javascript so any guidance would be much appreciated. I am suspecting that I would use something like below:

<ELEMENT onbeforeunload = "handler" ... >

Thanks in advance.

Split P.

+3  A: 

I'm not sure if this is something you're required to do by someone else, or something you think would be a good idea, but let me say that if you have the choice, please don't do this. If the user wants to leave the page, let them leave the page without telling them something they already know. Further, several modern browsers already have this functionality baked in, so it is just adding another layer of annoying for the user.

Having said that, take a look at this page, which will tell you everything you need to know.

What makes onbeforeunload quirky is that if you return ANYTHING at all in your event handler it will pop up a confirmation alert box asking the user if he or she is REALLY sure they want to leave the page

...

You can insert your own explanatory text BETWEEN those two lines by including a string on the return statement. For instance:

<script type="text/javascript">
  window.onbeforeunload = function () {
    return "The text you want the alert box to say.";
  }
</script>
Hooray Im Helping
+1. This says what I was going to say with significantly less snark.
Rob Allen
@Hooray,I need to do this in order to collect data. As I am doing this on a site that's already developed. Thanks for your input.@Rob, I do believe the "snark" would best be served to the website designer in this instance.
Split Personality
@Hooray, funnily enough, this little "quirk" will actually work to my advantage in this case. Thank you.
Split Personality
+1  A: 

2 1 thing (thanks @horray I'm helping).

You're better off detecting whether the form has been filled out programmatically, then if the user clicks to continue on without providing a critical piece of data, ask them for it. If they decide not to provide it, let them go.

For example:

var requiredField = document.getElementById("required");
if (requiredField.value == "")
{
    if (!confirm("Are you sure you want to go without saving your work?")){
       requiredField.focus();
    }
}

You could put that in click handlers for links, submit buttons or in the beforeunload event as you mentioned.

Rob Allen