Alert User If Data In Form Was Changed - jQuery Dirty

Alert User If Data In Form Was Changed - jQuery Dirty
File Size: 24.9 KB
Views Total: 5407
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   

The jQuery Dirty plugin detects if an HTML form is 'Dirty' and prompts the user to save changes before navigating away.

How to use it:

1. To use this plugin, include the jquery.dirty.js after jQuery library.

<script src="/path/to/cdn/jquery.slim.min.js"></script>
<script src="/path/to/dist/jquery.dirty.js"></script>

2. Call the function on your HTML form and trigger a function when the form gets 'Dirty'.

<form action="#" id="form">
  Form Fields Here
</form>
$("#form").dirty({
  onDirty: function(){
    alert("Dirty");
  }
});

3. Prevent the user from navigating away when there are unsaved changes on the page

$("#form").dirty({
  preventLeaving: true
});

4. Customize the alert message when the user tries to navigate away if the form is 'Dirty'.

$("#form").dirty({
  leavingMessage: "There are unsaved changes on this page which will be discarded if you continue."
});

5. Trigger a function when the form gets 'Clean'.

$("#form").dirty({
  onClean: function(){
    alert("Clean");
  }
});

6. API methods.

// detects if a form has been modified
// returns true or false
$("#form").dirty("isDirty");

// detects if a form is Clean
// returns true or false
$("#form").dirty("isClean");

// refreshes events
$("#form").dirty("refreshEvents");

// resets the form
$("#form").dirty("resetForm");

// sets the state to Clean
$("#form").dirty("setAsClean"); 

// shows modified form fields
$("#form").dirty("showDirtyFields");

Changelog:

v0.8.3 (2021-02-15)

  • Updated version including some dependency updates and an infrastructure change to build npm packages via GitHub actions

2020-09-20

  • Remove stopImmediatePropagation to prevent nuking other subscribers

2020-04-13

  • Mark form as clean if initial values are restored

This awesome jQuery plugin is developed by simon-reynolds. For more Advanced Usages, please check the demo page or visit the official website.