AngularJS directive for detecting pending changes before leaving/closing page - javascript

I have a problem. I have a registry form and many other forms.
Now I want to check whether the form is dirty and then I bring a confirm box if they really want to leave/close this page.
First of all, when I go back with the browser's back button and not with my other button ([button..] just 4 example) the confirmation box shows up two times and after two times confirming I'm still on the same page, just the form is resetted. When I press my own everything works fine.
Secondly, when I close the browser, my confirmation box shows up and afterwards the browsers confirmation box also shows up, but I only want one of them.
$scope.$on('$locationChangeStart', function (event, next, current) {
if ($scope.requestForm.$dirty) {
if (!$window.confirm('Unsaved Changes, leave Page?')) {
//cancel leaving view2
//works when clicking links, but doesn't work when using the back button
event.preventDefault();
}
} else {
}
});
$scope.$watch("requestForm.$dirty", function (newval) {
window.myGlobalDirtyFlag = newval;
});
window.onbeforeunload = function (e) {
if (window.myGlobalDirtyFlag === true) {
if (!$window.confirm('Unsaved Changes, close Page?')) {
//cancel leaving view2
//works when clicking links, but doesn't work when using the back button
return false;
} else {
}
}
};
$scope.$on("$destroy", function () {
window.myGlobalDirtyFlag = false;
});
May someone also have an idea how I bring this into an AngularJS directive, so I don't have to copy this code for every site where I have a form on it. (Every page only has 1 form, but every form name is different!)
My controllers are in seperate javascript files, (function blablaController() {}) and I pass this per routeProvider in my config file (templateUrl: blabla.html, controller: blabalController)
Regards,
Anthrax

Here is a service and directive that answers your question. Probably the only change you might consider making to it is using $window instead of window inside the service. As the instructions state, you'll just add the attribute unsaved-changes-warning to your form.
https://github.com/facultymatt/angular-unsavedChanges

Related

page reloads on changing the radio buttons

I'm working on a checkout process on a site. i wrote a piece of code to handle the steps, using java script and session storage. session storage keeps the current step. i wrote a function to stay on the same step on reloading the page.
it works fine, but there is two radio buttons on one of steps that user can choose the payment method using them. when user chooses one of them, page reloads but the function doesn't get called. :/ this is the function:
jQuery(document).ready(function() {
if (sessionStorage.checkoutstepHolder > 0) {
cartButtonHandler("onLoad");
}
});
the question is, why the function gets called on reloads caused by refreshing, but not on reloads caused by choosing the radio buttons?
maybe the radio button doesn't reload the page, maybe its doing something else :/
I would use a seperate function for this, because you use it on multiple occasions.
jQuery(document).ready(function() {
ReloadFunction();
});
function ReloadFunction() {
if (sessionStorage.checkoutstepHolder > 0) {
cartButtonHandler("onLoad");
}
}
On radiobutton change:
jQuery(document).on('change', '#radiobuttonID', function(){
ReloadFunction();
});

AngularJS when user presses back button

I've search all round and it seems I can't get a clear simple answer on this.
Basically I'm having problems with a search/filter field, user enters text and it filters that page. The filter works on every page.
Now when they press any navigation item it clears the search text / model value. I had to manually fire onclick events for this and create a function.
My problem is, is that when the user pressed the browser 'back button' the input text is not getting cleared.
Are there any simple events like:
if(usersPressedBackButton){
//Do stuff
}
Add this code into your controller:
$scope.$on('$locationChangeStart', function(event, next, current) {
if ($scope.yourinputfield.$dirty) {
$scope.yourinputfield = "";
$scope.yourinputfield.$setPristine();
}
});
No one could provide a clear answer on this, so I created my own.
I had a create a boolean that detected when the user searched form another page.
Parent Controller:
$scope.searchFilterText = '';
$scope.fromSearchClick = false;
$scope.$on('$locationChangeStart', function()
{
if(!$scope.fromSearchClick){
$scope.clearFilterSearchText();
}
$scope.fromSearchClick = false;
});
Child Controller - Or page you don't/do want the search to be cleared.
//In any function
$scope.$parent.fromSearchClick = true;

How to add history to jQuery UI tabs using a back button

I've got a PHP file with 5 tabs (jquery ui). Tab four and five contain
forms. Forms and tab work fine - expect to this: I submit the form (POST
method not XHR), then click the right mouse button (Firefox and IE behave
identical) and select back and then select tab five in the page by mouse
click the entered form data is still available.
I try to build a link, that is more convenient for the user.
<a href="#" onClick='history.back();$("#tabs").tabs("select","4");'>modify</a>
If click on my modify link, it still jumps back to tab one and the form fields in tab five are empty.
I read several posts about jQuery UI tabs and the back button, but all seem not to address my problem.
Where is my fault and is the difference between doing this steps by hand and my link with JS?
Javascript stops executing once you leave the page that it's running on -- the second half of your onClick handler never runs.
Following from the comments here is a function that will remember what your last tab was that you selected. It does rely on you using a set "Back" button.
The problem you will find, as far as I can see, is that you can't intercept a user clicking the browser back button. I have found that creating an obvious and clear back button on the site does the job and the feedback I have had so far on our sites seem to back that up.
The function is:
$(function() {
var $previousTab = 0;
var $backButtonUsed = false;
// Initialise tabs
$("#tabs").tabs();
$("#tabs").bind("tabsselect", function(event, ui) {
if ($backButtonUsed)
{
$backButtonUsed = false;
} else {
$previousTab = $("#tabs").tabs('option', 'selected');
}
return true;
});
$("#back").live('click', function() {
$backButtonUsed = true;
$("#tabs").tabs({ selected: $previousTab });
return true;
});
});​
I have also included this in a JSFiddle, so you can see it in action with the HTML and jQuery UI Tabs.
Let me know what you think.

jQuery Exit Popup Redirect?

So I've been looking around for hours, testing multiple versions, testing some of my own theories and I just can't seem to get it working.
What I'm trying to do is use alert or confirm (or whatever works) so popup a dialog when a user tries to navigate away from a purchase form. I just want to ask them "Hey, instead of leaving, why not get a free consultation?" and redirect the user to the "Free Consultation" form.
This is what I have so far and I'm just not getting the right results.
$(window).bind('beforeunload', function(){
var pop = confirm('Are you sure you want to leave? Why not get a FREE consultation?');
if (pop) {
window.location.href('http://www.mydomain/free-consultation/');
} else {
// bye bye
}
});
$("form").submit(function() {
$(window).unbind("beforeunload");
});
This is showing confirm dialog to user, want to stay or leave page. Not exactly what you looking for but maybe it will be useful for start.
function setDirtyFlag() {
needToConfirm = true; //Call this function if some changes is made to the web page and requires an alert
// Of-course you could call this is Keypress event of a text box or so...
}
function releaseDirtyFlag() {
needToConfirm = false; //Call this function if dosent requires an alert.
//this could be called when save button is clicked
}
window.onbeforeunload = confirmExit;
function confirmExit() {
if (needToConfirm)
return "You have attempted to leave this page. If you have made any changes to the fields without clicking the Save button, your changes will be lost. Are you sure you want to exit this page?";
}
Script taken from http://forums.devarticles.com/showpost.php?p=156884&postcount=18
Instead of using the beforeunload and alert(), I decided to check whether or not the users mouse has left the document. See code below:
$(document).bind('mouseleave', function(event) {
// show an unobtrusive modal
});
Not sure whether it will help.
You need to stop the propagation before showing the Confirm / Alert.
Please refer http://jonathonhill.net/2011-03-04/catching-the-javascript-beforeunload-event-the-cross-browser-way/
Look at the last comment.
Try this:
window.onunload = redirurl;
function redirurl() {
alert('Check this Page');
window.location.href('http://www.google.com');
}

How do I stop a page from unloading (navigating away) in JS?

Does anyone know how to stop a page from reloading or navigating away?
jQuery(function($) {
/* global on unload notification */
warning = true;
if(warning) {
$(window).bind("unload", function() {
if (confirm("Do you want to leave this page") == true) {
//they pressed OK
alert('ok');
} else {
// they pressed Cancel
alert('cancel');
return false;
}
});
}
});
I am working on an e-commerce site at the moment, the page that displays your future orders has the ability to alter the quantities of items ordered using +/- buttons. Changing the quantities this way this doesn't actually change the order itself, they have to press confirm and therefore committing a positive action to change the order.
However if they have changed the quantities and navigate away from the page I would like to warn them they are doing so in case this is an accident, as the changed quantities will be lost if they navigate away or refresh the page.
In the code above I am using a global variable which will be false by default (its only true for testing), when a quantity is changed I will update this variable to be true, and when they confirm the changes I will set it to false.
If warning is true and the page is unloaded, I offer them a confirmation box, if they say no they would like to stay on this page I need to stop it from unloading. return false isn't working, it still lets the user navigate away (the alerts are there for debugging only)
Any ideas?
onbeforeunload is the one you want; your function "should assign a string value to the returnValue property of the Event object and return the same string". Check the docs from Microsoft and Mozilla for details.
The string you return will be used by the browser to present the user with a custom confirm box, allowing them to refuse to stay there if they so choose. It has to be done that way to prevent malicious scripts causing a Denial-of-Browser attack.
This code warns as per Natalie's suggestion, but disables the warning if a form on the page was submitted. Uses JQuery.
var warning = true;
window.onbeforeunload = function() {
if (warning) {
return "You have made changes on this page that you have not yet confirmed. If you navigate away from this page you will lose your unsaved changes";
}
}
$('form').submit(function() {
window.onbeforeunload = null;
});
you want to use the onbeforeunload event.
window.onbeforeunload = confirmExit;
function confirmExit()
{
return "You have attempted to leave this page. If you have made any changes to the fields without clicking the Save button, your changes will be lost. Are you sure you want to exit this page?";
}
window.onbeforeunload = function() {
if (warning) {
return `You have made changes on this page that you have not yet confirmed.
If you navigate away from this page you will lose your unsaved changes`;
}
}
Isn't supported in chrome, safari and opera
As said in this comment, nothing in jQuery binds to the beforeunload event.
#karim79: no it doesn't. There isn't anything in jQuery that binds to the beforeunload function; "unload" binds to the "unload" event. Search the source if you don't believe me ;-) – NickFitz
So you have to use pure Javascript to bind a function to the beforeunload event.
var warning = true;
$("form").submit(function() {
warning = false;
});
$('#exit').click(function() {
window.location.replace('https://stacksnippets.net/js')
});
window.onbeforeunload = function() {
if(warning) {
return true;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<form>
<input type="submit">
</form>
Try using e.preventDefault() instead of returning false. 'e' would be the first argument to your unload callback.

Categories