Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting Unsaved Changes

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.

like image 306
tbreffni Avatar asked Oct 01 '08 00:10

tbreffni


People also ask

How to detect unsaved changes in JavaScript?

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.

How to warn user before leaving page JavaScript?

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 || !

What is markAsPristine?

markAsPristine() Marks the control as pristine. Angular documentation for form control's validatior api— https://angular.io/api/forms/AbstractControl.

What is updateValueAndValidity?

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.


1 Answers

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.

like image 90
Aaron Powell Avatar answered Oct 15 '22 08:10

Aaron Powell