Search code examples
javascriptjqueryasp.net-mvckendo-uikendo-asp.net-mvc

Jquery before leave the page unsaved changes alert


I have a jquery dialog and it has some Kendo textboxes, dropdownlists and comboboxes. I want it to warn users before closing the dialog with unsaved changes if users made changes. It currently does warn when I make some changes and try to close the modal. But the thing is, it just warns all the time if I even change one text box click on other text boxes to edit. I just want it to warn users only once when they finish modifying and try to close the dialog.

Here is my code

    $('.ui-button').mousedown(function () {
        if ($(":input").change(function (e) {
            var dirtyFlagMsg = confirm('Are you sure you want to close without saving?');
            if (dirtyFlagMsg == true) {
                $("#popUpEdit").dialog("close");
                $("#popUpNew").dialog("close");
            }
            else e.preventDefault();
        }));
    });

Solution

  • First of all, You are mixing pears and apples, jquery dialog and onbeforeunload are two diferent things. I think you want to close the dialog and not the window (title of question is misleading).

    You don't need to track every mousedown event, you need to call function on dialog before close event.

    In beforeClose event of dialog check it there is dirty fields, if there is a dirty fields pop up confirmation message, otherwise return true and dialog will call close event.

    Something like this (not tested):

    $("#dialog").dialog({
       beforeClose: function(){
         var isDirty = //logic for dirty check of inputs
         if(isDirty){
            if(confirm("Are you sure you want to close without saving?")){
                return true;
            } else {
                return false;
            }
         }
    
         return true;
       }
    });
    

    Of course im using plain browser confirmation so you will need to use your own logic for dialog confirmation. Hope it helps!