Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8296765
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 8, 20262026-06-08T15:08:44+00:00 2026-06-08T15:08:44+00:00

I’m writing a lightweight jQuery plugin to detect dirty forms but having some trouble

  • 0

I’m writing a lightweight jQuery plugin to detect dirty forms but having some trouble with events. As you can see in the following code, the plugin attaches an event listener to ‘beforeunload’ that tests if a form is dirty and generates a popup is that is the case.

There is also another event listener attached to that form’s “submit” that should in theory remove the ‘beforeunload’ listener for that specific form (i.e. the current form I am submitting should not be tested for dirt, but other forms on the page should be).

I’ve inserted a bunch of console.log statements to try and debug it but no luck. Thoughts?

  // Checks if any forms are dirty if leaving page or submitting another forms
  // Usage:
  // $(document).ready(function(){
  //    $("form.dirty").dirtyforms({
  //      excluded: $('#name, #number'),
  //      message: "please don't leave dirty forms around"
  //    });
  // });


  (function($) {

    ////// private variables //////

    var instances = [];

    ////// general private functions //////

    function _includes(obj, arr) {
        return (arr._indexOf(obj) != -1);
    }

    function _indexOf(obj) {
      if (!Array.prototype.indexOf) {
        Array.prototype.indexOf = function (obj, fromIndex) {
          if (fromIndex == null) {
            fromIndex = 0;
          } else if (fromIndex < 0) {
            fromIndex = Math.max(0, this.length + fromIndex);
          }
          for (var i = fromIndex, j = this.length; i < j; i++) {
            if (this[i] === obj)
            return i;
          }
          return -1;
        };
      }
    }

    ////// the meat of the matter //////

    // DirtyForm initialization
    var DirtyForm = function(form, options) {

      // unique name for testing purposes
      this.name = "instance_" + instances.length

      this.form = form;

      this.settings = $.extend({
        'excluded'  : [],
        'message'   : 'You will lose all unsaved changes.'
        }, options);

        // remember intial state of form
        this.memorize_current();

        // activate dirty tracking, but disable it if this form is submitted
        this.enable();
        $(this.form).on('submit', $.proxy(this.disable, this));

        // remember all trackable forms
        instances.push(this);
      }

      // DirtyForm methods
      DirtyForm.prototype = {

        memorize_current: function() {
          this.originalForm = this.serializeForm();
        },

        isDirty: function() {
          var currentForm = this.serializeForm();
          console.log("isDirty called...")
          return (currentForm != this.originalForm);
        },

        enable: function() {
          $(window).on('beforeunload', $.proxy(this.beforeUnloadListener, this));
          console.log("enable called on " + this.name)
        },

        disable: function(e) {
          $(window).off('beforeunload', $.proxy(this.beforeUnloadListener, this));
          console.log("disable called on " + this.name)
        },

        disableAll: function() {
          $.each(instances, function(index, instance) {
            $.proxy(instance.disable, instance)
          });
        },

        beforeUnloadListener: function(e) {
          console.log("beforeUnloadListener called on " + this.name)
          console.log("... and it is " + this.isDirty())
          if (this.isDirty()) {
            e.returnValue = this.settings.message;
            return this.settings.message;
          }
        },

        setExcludedFields: function(excluded) {
          this.settings.excluded = excluded;
          this.memorize_current();
          this.enable();
        },

        serializeForm: function() {
          var blacklist = this.settings.excludes
          var filtered = [];
          var form_elements = $(this.form).children();

          // if element is not in the excluded list
          // then let's add it to the list of filtered form elements
          if(blacklist) {
            $.each(form_elements, function(index, element) {
              if(!_includes(element, blacklist)) {
                filtered.push(element);
              }
            });
            return $(filtered).serialize(); 
          } else {
            return $(this.form).serialize();
          } 
        }
      };

      ////// the jquery plugin part //////

      $.fn.dirtyForms = function(options) {
        return this.each(function() {
          new DirtyForm(this, options);
        });
      };

    })(jQuery);

[EDIT]

I ended up fixing this by using jQuery’s .on() new namespace feature to identify the handler. The problem was that I was passing new anonymous functions as the handler argument to .off(). Thanks @FelixKling for your solution!

    this.id = instances.length

    [...]

    enable: function () {
        $(window).on('beforeunload.' + this.id, $.proxy(this.beforeUnloadListener, this));
    },

    disable: function () {
        $(window).off('beforeunload.' + this.id);
    },
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-08T15:08:47+00:00Added an answer on June 8, 2026 at 3:08 pm

    Whenever you are calling $.proxy() it returns a new function. Thus,

    $(window).off('beforeunload', $.proxy(this.beforeUnloadListener, this));
    

    won’t have any effect, since you are trying to unbind a function which was not bound.

    You have to store a reference to the function created with $.proxy, so that you can unbind it later:

    enable: function() {
        this.beforeUnloadListener = $.proxy(DirtyForm.prototype.beforeUnloadListener, this);
        $(window).on('beforeunload', this.beforeUnloadListener);
        console.log("enable called on " + this.name)
    },
    
    disable: function(e) {
        $(window).off('beforeunload', this.beforeUnloadListener);
        console.log("disable called on " + this.name)
    },
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have a jquery bug and I've been looking for hours now, I can't
I'm having trouble keeping the paragraph square between the quote marks. In firefox the
I have just tried to save a simple *.rtf file with some websites and
I want to count how many characters a certain string has in PHP, but
For some reason, after submitting a string like this Jack’s Spindle from a text
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I am reading a book about Javascript and jQuery and using one of the
I have a French site that I want to parse, but am running into
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.