0

I'm working in a legacy ASP.NET/MVC project that is using a bit of jQuery to provide an unsaved changes warning. There's a utils.js file that's included on every page that contains:

// Has the user made changes on the form?
var formHasModifications = false;

$(document).ready(function () {

    // We want to trigger the unchanged dialog, if the user has changed any fields and hasn't saved
    $(window).bind('beforeunload', function () {
        if (formHasModifications) {
            return "You haven't saved your changes.";
        }
    });

    // If a field changes, the user has made changes
    $("form:not(.noprompt)").change(function (event) {
        formHasModifications = true;
    });

    // If the form submits, the changes are saved
    $("form:not(.noprompt)").submit(function (event) {
        formHasModifications = false;
    });

    // $(document).ready() may make changes to fields, so we need to clear the flag
    // immediately after it returns
    setTimeout(function() {
        formHasModifications = false;
    }, 1);

});

The problem? The .submit() event fires, and is caught, on every submit - including on submits that don't actually submit the data.

That is, if there is a validation error, clicking on the submit button leaves the user on the page, with unsaved changes, and displayed validation failure messages, but it also clears the formHasModifications flag.

The result is that if the user makes changes to one or more inputs, clicks "submit", gets validation errors, then navigates to a different page without fixing them, and resubmitting, they do not see the unsaved changes dialog, even though they do have unsaved changes.

This is, as I said, a legacy app, and I'm not interested in making fundamental structural changes. But if there's some way of being able to tell, in jQuery, whether a submit event succeeded or failed, I'd really like to know.

Jeff Dege
  • 11,190
  • 22
  • 96
  • 165

1 Answers1

0

OK, as Terry pointed out, it depends upon what we're using for validation.

In our case, we're using jquery.validate. And with this, we can call .valid() on the form to determine whether the form passed validation:

// If the form successfully submits, the changes are saved
$("form:not(.noprompt)").submit(function (event) {
    if ($(this).valid()) {
        formHasModifications = false;
    }
});
Jeff Dege
  • 11,190
  • 22
  • 96
  • 165