1

I have a website which has form fields that can be updated when the user hits the save button by an onSave() JavaScript function shown here:

function onSave(){
        if(validateFields()){
            submitted = true;
            document.forms[0].submit();

        }

        return false;
}

This function works great, but I recently tried to add a pop up box that appears when a user tries to navigate away from the webpage using the following code:

if (submitted == false){
    window.onbeforeunload =  function(){
        return('You are leaving this page without saving, any changes you have made will be lost. If you wish to save your changes, cancel this warning and save the page. Otherwise just click leave page.');
    }
}

Unfortunately, this pop up box also appears when the user clicks the save button. So after finding these previous posts: Post 1, and Post 2, I rewrote my code to look like this:

var submitted = false;
var formHasChanged = false;

if($document.change()){
    formChange == true;     
}

function onSave(){
    if(validateFields()){
        submitted = true;
        document.forms[0].submit();

    }

    return false;
}


if (!submitted  && ! formHasChanged){
    window.onbeforeunload =  function(){
        return('You are leaving this page without saving, any changes you have made will be lost. If you wish to save your changes, cancel this warning and save the page. Otherwise just click leave page.');
    }
}

But now the pop up box is not appearing at all. I have tried putting the two functions in separate script tags, and the pop up box appears when hitting the save button and the back button. Is there any other way to only make the pop up box appear when hitting the back button? Or is my code flawed?

Community
  • 1
  • 1

2 Answers2

0

Put the !submitted check inside of the event handler.

window.onbeforeunload =  function(){
    if (submitted == false){
        return('You are leaving this page without saving, any changes you have made will be lost. If you wish to save your changes, cancel this warning and save the page. Otherwise just click leave page.');
    }
}
Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
0

Try:

<SCRIPT LANGUAGE="JavaScript">
    var submitted = false;
    var formHasChanged = false;


    function onSave(){
        if(validateFields()){
            submitted = true;
            document.forms[0].submit();

        }

        return false;
    }


</script>
<script language ="JavaScript">


    window.onbeforeunload =  function(){
        if(!submitted){
            return('You are leaving this page without saving, any changes you have made will be lost. If you wish to save your changes, cancel this warning and save the page. Otherwise just click leave page.');
        }

    }


</SCRIPT>
Turtle
  • 1,369
  • 1
  • 17
  • 32