Show alert when moving to other page without saving current page

Show alert when moving to other page without saving current page

Hi,

My requirement is, I have multiple pages in tab format. If i am on first page in edit mode and change any control's value and without saving information i click on other tab that particular time a popup should appear showing validation message say "you are moving without save and it will loos all changes either click ok to loose the changes and move to other page or click cancel to remain on the current page."

I tried using

var isDirty = false; 
    var msg = 'This page has unsaved changes.\n\nClick OK to abandon the changes and leave the page.\n\nClick Cancel to stay on the page so that you can save your changes.'; 
 
    $(document).ready(function () 
    { 
        $(':input').change(function () 
        { 
            if (!isDirty) 
            { 
                isDirty = true; 
            } 
        }); 
 
        window.onbeforeunload = function () 
        { 
          
            if (isDirty) return msg; 
        }; 
    });

but message appears everytime even if i don't change anything on current page.

Any help would be appreciated.

Thanks