views:

43

answers:

1

I have created some code to popup a confirm dialog if a user tries to leave a page without saving their changes. However, I don't want the confirmation dialog to popup if the user has clicked the "Save" button.

I have some code at the top of my file which looks like this:

var confirmClose = false;
window.onbeforeunload = function(evt) {
    if (confirmClose == true) {
        message = "There are unsaved changes on this page.  Are you sure you wish to leave?";
        if (typeof evt == 'undefined') {
            evt = window.event;
        }
        if (evt) {
            evt.returnValue = message;
        }
        return message;
     }
}

Further down on the page I have a link which looks like this:

<a href="javascript:confirmClose=false;$('#stockForm').submit()" title="Save" class="button positive" id="stockFormSubmit">Save</a>

However, this doesn't seem to work - it doesn't seem to change the value of confirmClose, and changing it to window.confirmClose didn't help either.

What am I doing wrong here?

+1  A: 

This will work:

<script type="text/javascript">
var confirmClose = false;
window.onbeforeunload = function(evt) {
    evt = evt || window.event;
    if (confirmClose === true) {
        message = "There are unsaved changes on this page.  Are you sure you wish to leave?";
       if (evt) {
           evt.returnValue = message;
       }
       return message;
   }
};
function saveAction() {
    confirmClose=false;
    $('#stockForm').submit();
    return false;
}

</script>
<a href="#" title="Save" class="button positive" id="stockFormSubmit">Save</a>

<script type="text/javascript">
   document.getElementById( 'stockFormSubmit' ).onclick = saveAction;
</script> 
Jacob Relkin
I actually tried that as well (my code was exactly the same, except I called the function `submitForm()`), but it tells me that "submitForm is not defined" even though it is all spelt correctly (I copy / pasted the name into the link).
a_m0d
I got it fixed - I didn't realise that I was defining both `submitForm()` and `confirmClose` within a `$(function() {})` jQuery block - moving them both out of that solved my problem. Thanks for your help.
a_m0d