Alert User If Data In Form Was Changed - jQuery Dirty

Alert User If Data In Form Was Changed - jQuery Dirty

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

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

<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" 
        integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" 
        crossorigin="anonymous">
</script>
<script src="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");

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

  • Publication date: 02.02.2019
  • Source