Check if changes saved before unload

I have the following JavaScript

EDIT: included assignments for changesSaved

 var changesSaved = true;

    $(document).ready(function () {

        $(".applyChanges").click(function (e) {
            var id = (this).id;
            var dayofweek = document.getElementById("dayofweek" + id).value;
            var hour = document.getElementById("hour" + id).value;
            var duration = document.getElementById("duration" + id).value;
                url: '@Url.Action("ApplyChanges")',
                type: 'POST',
                data: {
                    id: id,
                    dayofweek: dayofweek,
                    hour: hour,
                    duration: duration
                success: function (data) {
                    changesSaved = false;

window.onbeforeunload = function () {
    if (changesSaved == true) {
        return true;
    } else {
        return ("You havent saved your changes. Are you sure you want to leave the page?")

but the message is being prompted regardless of what changesSaved is set too.

What actually I actually get is the following:

enter image description here

or if changesSaved is set to false it says false instead.

Can I not do this ?


<body onbeforeunload="return bye()">

function bye(){
    if(changesSaved) {
        return "You havent saved your changes."

This is how I do it.

or in pure JavaScript:

window.onbeforeunload = function() {
    if (changesSaved) {
        return "You haven't saved your changes.";
window.onbeforeunload = function () {
     var changesSaved = confirm("You havent saved your changes. Are you sure you want to leave the page?");
    if (changesSaved) {
        return true;
    } else {
        return false;


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.