Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prompt confirm before Leaving edited html form

If user tries to leave unsaved edited form, a message box pop-up

"This page is asking you to confirm that you want to leave - data you have entered may not be saved. Leave Page and Stay on Page"

Can we invoke this confirmation box through some special function of browser? I want to implement it in AngularJS application

enter image description here

like image 571
Anand Avatar asked Nov 26 '12 13:11

Anand


People also ask

How can I be alerted before leaving a page?

How to warn user before leaving page JavaScript? To make a warning alert or confirm dialog display when the user reloads the page or closes a tab using javascript, we can use window. addEventListener() and beforeunload events like the script above.

How to display warning before leaving the web page with unsaved changes using JavaScript?

How to display warning before leaving the web page with unsaved changes using JavaScript ? The onbeforeunload event handler is used for processing beforeunload events. This event is fired whenever a window is about to unload its resources.

How to trigger beforeunload event?

The beforeunload event is fired when the window, the document and its resources are about to be unloaded. The document is still visible and the event is still cancelable at this point. This event enables a web page to trigger a confirmation dialog asking the user if they really want to leave the page.

Which jquery event method will show an alert before the user leaves the page?

The onbeforeunload event fires when the document is about to be unloaded. This event allows you to display a message in a confirmation dialog box to inform the user whether he/she wants to stay or leave the current page. The default message that appears in the confirmation box, is different in different browsers.


1 Answers

Warlock's answer is partly right, but in doing so, you'd break testability.

In Angular, you'd want to use $window, and you'll want to watch $dirty on your form. You'll need to have a named form, notice name="myForm" below. Then you can $watch $dirty on the form in your $scope:

app.controller('MainCtrl', function($scope, $window) {
  $scope.name = 'World';
  var win = $window;
  $scope.$watch('myForm.$dirty', function(value) {
    if(value) {
      win.onbeforeunload = function(){
        return 'Your message here';
      };
    }
  });
});

HTML

<form name="myForm">
  Name: <input type="text" ng-model="name"/>
</form>

Here's a plunk to demonstrate: http://plnkr.co/edit/3NHpU1

like image 69
Ben Lesh Avatar answered Sep 27 '22 22:09

Ben Lesh