Forum Moderators: open

Message Too Old, No Replies

Confirm Close

If Cancel, what should I use instead of "return false;"

         

ntbgl

2:20 am on Jan 24, 2009 (gmt 0)

10+ Year Member



I have a page with a long form. I am implamenting a javascript confirmation in case the user accidentally closes, refreshes, clicks back, or any other option that would make the user loose all the data entered in.

This is the script I have in the document's head:

<script type="text/javascript">
window.onbeforeunload=function(){
var answer=confirm("You tried to close, reload or move away from this page. You will loose all your data if you did not save or print. \n\n OK - Loose all data. \n Cancel - Return to your document.");
if(!answer) return false;}
</script>

If the user clicks OK, then everything is fine, the action the user does works as expected.

However, if the user clicks CANCEL, then a second confirmation box comes up:

"Are you sure you want to navigate away from this page?
false
Press OK to continue, or Cancel to stay on the current page."

I don't want this second box to appear, I just want if the user clicks on the first CANCEL to be taken back to the page.

I assess this is based on my line "if(!answer) return false;"

What should I put there instead?

Thanks

Fotiman

3:42 am on Jan 24, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



onbeforeunload works a little differently.

<script type="text/javascript">
window.onbeforeunload = function () {
return "You tried to close, reload or move away from this page. You will loose all your data if you did not save or print. \n\n OK - Loose all data. \n Cancel - Return to your document.";
}
</script>

Fotiman

3:44 am on Jan 24, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



The function that you assign to onbeforeunload should return a string, which is the string that will be displayed in the dialog box. You don't use confirm, the browser will create the buttons. Also, you can't be certain the browser will use "Ok" and "Cancel" for the buttons... I think Google Chrome uses buttons that say "Leave this Page" and "Stay on this Page", so you should probably change your text message to not refer to "Ok" and "Cancel" buttons.

[edited by: Fotiman at 5:01 am (utc) on Jan. 24, 2009]