Original Value Tracking
Store the original form values with .data() so you can detect changes or restore them with a "Cancel" button.
Store the original form values with .data() so you can detect changes or restore them with a "Cancel" button.
// 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")
);
}
Prompt users with unsaved changes before navigation using the beforeunload event.