I have a requirement to implement an "Unsaved Changes" prompt in an ASP .Net application. If a user modifies controls on a web form, and attempts to navigate away before saving, a prompt should appear warning them that they have unsaved changes, and give them the option to cancel and stay on the current page. The prompt should not display if the user hasn't touched any of the controls.
Ideally I'd like to implement this in JavaScript, but before I go down the path of rolling my own code, are there any existing frameworks or recommended design patterns for achieving this? Ideally I'd like something that can easily be reused across multiple pages with minimal changes.
To alert for unsaved changes in form with JavaScript, we can track changes done to inputs in a form. Then we can set the window. onbeforeunload property to a function that checks the changing state of the input and returns an alert message if there're changes.
One solution is to use the beforeunload event in combination with a "dirty" flag, which only triggers the prompt if it's really relevant. var isDirty = function() { return false; } window. onload = function() { window. addEventListener("beforeunload", function (e) { if (formSubmitting || !
markAsPristine() Marks the control as pristine. Angular documentation for form control's validatior api— https://angular.io/api/forms/AbstractControl.
updateValueAndValidity allows you to modify the value of one or more form controls and the flag allows you to specify if you want this to emit the value to valueChanges subscribers.
Using jQuery:
var _isDirty = false; $("input[type='text']").change(function(){ _isDirty = true; }); // replicate for other input types and selects
Combine with onunload
/onbeforeunload
methods as required.
From the comments, the following references all input fields, without duplicating code:
$(':input').change(function () {
Using $(":input")
refers to all input, textarea, select, and button elements.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With