Prevent page leaving and capture Leave button Jquery - javascript

I wish to prevent a user from leaving a page before clicking on submit button.And when he confirm leave i want to execute something (delayed leave).
i use this function
window.addEventListener('beforeunload', function(e) {
var myPageIsDirty = "d";
if (myPageIsDirty) {
e.preventDefault();
e.returnValue = '';
}
});
This surely warns the user. But my requirement to handle the leave button click event and do something

leave button confirmation can be done by:
Submit

Related

Resuming default behaviour after preventDefault()

I've written a small jQuery plugin which is designed to ask the question, "Are you sure?" when clicking on a link or submitting a form.
It's used like this:
Link
Or like this:
<form action="link.php" method="post">
<button class="confirm">Submit</button>
</form>
What I am doing is using preventDefault() to prevent the default behavior when the anchor or button is clicked. I then display a confirm dialogue where the user has to click either OK or Cancel.
If the user clicks Cancel then nothing happens (as expected).
However, if the user clicks OK I am firing the click event again, and using a flag that was set first time around to not prevent the default behaviour second time around (I'm instead returning true). Except that it's not working. Clicking either OK or Cancel in the confirm dialogue doesn't do anything.
The plugin is below:
(function($) {
$.fn.fw_confirm = function(options) {
// Flag to check for the first click event
var paused = false;
return this.on("click", function(e) {
// The anchor or the button that was clicked
var button = $(this);
// If this is the second click event, the user must have confirmed so return true
if (paused == true) {
// Reset the flag
paused = false;
// This isn't working, or at least it's not submitting the form or proceeding to the URL of the hyperlink when I would expect it to
return true;
}
// First time around prevent the default behavior
e.preventDefault();
e.stopImmediatePropagation();
// Set the flag to true, ready for the second click event
paused = true;
if (confirm("Are you sure?")) {
// The user is certain, so trigger the click event again
return button.trigger("click");
} else {
// The user cancelled, reset the flag
paused = false;
return;
}
});
}
})(jQuery);

Prevent double submission with prevent window event issue

I'm using the following function to prevent double submissions:
$("#form").submit(function () {
var form = $(this);
form.find("input[type=submit]").attr("disabled", "disabled")
form.find("input[type=submit]").attr("value", "Processing");
});
It works fine, but then I have the following code which triggers an alert to avoid accidentally leaving the page:
function goodbye(e) {
if(!e) e = window.event;
//e.cancelBubble is supported by IE - this will kill the bubbling process.
e.cancelBubble = true;
e.returnValue = '¿DO YOU REALLY WANT TO LEAVE THIS PAGE?'; //This is displayed on the dialog
//e.stopPropagation works in Firefox.
if (e.stopPropagation) {
e.stopPropagation();
e.preventDefault();
}
}
window.onbeforeunload=goodbye;
The problem is if the user clicks submit and the realizes he didnt want to leave the page and clicks on stay on this page instead, the submit button is still disabled.
How could I re-enable it upon clicking stay on this page?
Thanks!
The button problem
You want to disable and enable the submit button so you know you going to touch the same kind of function and object twice, it is better to make advantage out of this in a function
function disableSubmit(form, enabled){
var submit = form.find("input[type=submit]"),
dataVar = enabled !== true ? "processing-message" : "send-message",
message = submit.data(dataVar);
submit.prop('disabled', (enabled !== true) );
submit.val(message);
}
I could make it even more generic for using it on each form. But the message in the button will display whatever you put in the data-attribute.
Cancel Submit
There is a problem with cancellation of an onbeforeunload event; there is no callback for it. The solution I came with is using a timeout. Since you don't know if the person canceled or not, I think 2 seconds is enough for the page to submit.
You have to have 2 seconds patient to get the submit button enabled again. But you can adjust it all you want of course
if (e.stopPropagation) {
setTimeout(function () {
disableSubmit(formObject, true);
}, 2000);
e.stopPropagation();
e.preventDefault();
}
The JSFiddle example

Preventing users from accidentally navigating away from unsaved pages

I got the snippet below from this SO post, and it works when a user tries to reload the page or close the browser etc. but if the user clicks on a link then it lets them naivagate away, and then incorrectly starts displaying the message on the wrong page. I am using pjax for the links.
$(document).ready(function () {
$('textarea').change(function () {
window.onbeforeunload = function () { return "Your changes to the survey have not been saved?" };
});
});
You should use onbeforeunload like this, inconditionally:
<script type="text/javascript">
saved=true; // initially, it is saved (no action has been done)
window.onbeforeunload = confirmExit;
function confirmExit() {
if (!saved) {
return "You did not save, do you want to do it now?";
}
}
</script>
It is not safe to handle this event only when another event is fired. The onchange event of your textarea here probably don't fire before you click on a link so the window won't handle the onbeforeunload at all. The link will work as expected: you will get redirected.
To deal with the saved flag, you could listen to what happens in your textarea, for example, when the user is actually typing something:
$('textarea').keyup(function(){
saved=false;
});
Then, if you save the data in ajax, the save button could set it back to true:
$('#btnSave').click(function(){
// ajax save
saved=true;
});
Otherwise, it will load the next page with the saved flag on.
what about something like the following?
Listening on all <a> links and then, depending on whether the variable needToSave is set to true, showing the message or letting it go.
var needToSave = false; // Set this to true on some change
// listen on all <a ...> clicks
$(document).click("a", function(event){
if (needToSave == true) {
alert("You need to save first");
event.preventDefault();
return;
}
});
UPDATE (as per Roasted's suggestion) this should trigger the unload event every time the link is clicked and perform your existing logic:
// listen on all <a ...> clicks
$(document).click("a", function(event){
$(window).trigger("unload");
});
jsFiddle here - http://jsfiddle.net/k2fYM/

Exclude submit button from beforeunload event

I'm detecting form changes in a page, and so i've handled
$('#element').change(function(){
metaDataChange = true;
});
so that when the user leaves the page and a change was made in an input in a form. He/she will be alerted whether to leave or to stay on the page, just like in Facebook where you try to post a status and then you leave the page, a dialog box will be prompted giving you options to either leave or stay in the page.
$(window).on('beforeunload', function() {
if(metaDataChange === true || basicInfoChange === true){
return "You have unsaved changes, do you want to leave without saving?";
}
});
The code above works well however.. i want to exclude the submit button for this.
Because when i click "submit" and the behavior of the submit button means redirecting to another page. The user is prompted again with the same message when in fact he/she intends to save his/her changes.
How do i exclude the submit button from being caught in the beforeunload event of the window? I can hardly explain this... i hope it can be understood..Thanks!
$('#submitButton').click(function(){
metaDataChange = false;
...redirecting
});

Two button confirmations - Jquery

Currently I have a submit button that pops up a confirmation that allows the form data to be processed or not.
I need my other button on my form page called "Cancel" to have the same action. How could I expand this code to add a second confirmation to the same form?
these are my buttons on the form :
And this is my current code that works :
</script>
<script>
$(document).on('submit', "#signinform", function(e)
{
if (!confirm("By clicking 'OK' you will be placed in queue! Please take a seat."))
{
e.preventDefault();
return;
}
});
</script>
just to add on :
The submit is a submit BUTTON. the Cancel is just a href with a border around it.
also again
This works at the moment for just the submit button.
I need my other button on the form called "Cancel" to do the samething, as in if you hit Ok your submission data will be deleted, and then you will be returned back to the form. If you hit cancel then you will remain on the page.
I guess you simply need something like
$(document).on('click', "#cancelButtonID", function(e)
{
if (!confirm("By clicking 'OK' you cancel the submission and the form is cleared."))
{
e.preventDefault();
return;
}
else {
//Clear the form or perform whatever actions are needed
}
});
I think however that you may want to replace your cancel link with a proper <input type="reset"> button, as that will clear the form automatically when you let the default action happen. Then you should be able to get rid of the else section above.

Categories

Resources