0

I am attempting to simply capture when my form is dirty and if it has been changed, alert the user before they leave the page without saving.

Here is my current code:

 <script>
    var form = $('#MyForm'),
    originalForm = form.serialize()
    
    $(window).bind('beforeunload', function () {   
        if (form.serialize() != originalForm) {
            return 'You have unsaved changes';
        }          
    });
</script>

Nothing happens above. I can use beforeunload method just fine until I attempt to add the "dirty" field check, then nothing occurs.

Any help?

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Eli
  • 533
  • 1
  • 5
  • 24
  • https://stackoverflow.com/questions/11844256/alert-for-unsaved-changes-in-form – SKJ Aug 24 '22 at 20:01
  • That question deals with checking a single textbox, here I am attempting to check my entire form contents. – Eli Aug 24 '22 at 20:06
  • The code in your question appears to work fine: https://jsfiddle.net/RoryMcCrossan/jw0as5mc/. If it's not working for you then there's either some specific important details you've missed, or you've got an error in some other part of your codebase affecting this logic. I'd suggest starting by checking the devtools console for errors you can use to debug. – Rory McCrossan Aug 24 '22 at 20:23
  • In addition, note that `bind()` is deprecated. I'd strongly suggest you check which version of jQuery you're using (the latest is 3.6) and update your code to use `on()` instead. Also, as this has nothing to do with C# or Google Chrome, I've removed those tags. – Rory McCrossan Aug 24 '22 at 20:24

0 Answers0