Search code examples
javascriptasp.netprompt

Detecting Unsaved Changes


I have a requirement to implement an "Unsaved Changes" prompt in an ASP .Net application. If a user modifies controls on a web form, and attempts to navigate away before saving, a prompt should appear warning them that they have unsaved changes, and give them the option to cancel and stay on the current page. The prompt should not display if the user hasn't touched any of the controls.

Ideally I'd like to implement this in JavaScript, but before I go down the path of rolling my own code, are there any existing frameworks or recommended design patterns for achieving this? Ideally I'd like something that can easily be reused across multiple pages with minimal changes.


Solution

  • Using jQuery:

    var _isDirty = false;
    $("input[type='text']").change(function(){
      _isDirty = true;
    });
    // replicate for other input types and selects
    

    Combine with onunload/onbeforeunload methods as required.

    From the comments, the following references all input fields, without duplicating code:

    $(':input').change(function () {
    

    Using $(":input") refers to all input, textarea, select, and button elements.