开发者

Prompt User to Fill in Form Prior to Leaving Web Page - via Javascript

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 u开发者_如何学Pythonser 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.


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>


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜