SyntaxStudy
Sign Up
jQuery Tracking Original Form Values
jQuery Intermediate 4 min read

Tracking Original Form Values

Original Value Tracking

Store the original form values with .data() so you can detect changes or restore them with a "Cancel" button.

Example
// Store original values when form loads
$("form :input").each(function() {
  $(this).data("original", $(this).val());
});

// Cancel: restore originals
$("#cancel").on("click", function() {
  $("form :input").each(function() {
    $(this).val($(this).data("original"));
  });
});

// Check if changed
function hasChanges() {
  return $("form :input").toArray().some(el =>
    $(el).val() !== $(el).data("original")
  );
}
Pro Tip

Prompt users with unsaved changes before navigation using the beforeunload event.