I'm trying to implement a warning for the users in case they are leaving the form without saving.
The warning dialog works as expected but with the only exception that when the user chooses to 'Stay on Page', the selected side menu entry changed to the one the user clicked on (form is the same).
How can I make sure that the same menu item is still selected once the user chooses to 'Stay on Page'?
var warnMessage = "Unsaved changes. Do you really want to leave the page?";
$(document).ready(function () {
$('a.k-link').on('click', function () {
window.onbeforeunload = function () {
if (isDirty) return warnMessage;
}
});
});
You might find it easier (and possibly more consistent across browsers) to use a confirm prompt (remember, it's a blocking dialog).
<script>
var warnMessage = "Unsaved changes. Do you really want to leave the page?";
$('a.k-link').on('click', function (e) {
if (isDirty && !confirm(warnMessage)) {
e.preventDefault();
}
});
</script>
There are at least two reasons to avoid onbeforeunload:
The spec doesn't require a browser to display the message you
provide, and not all browsers do, and
the correct event is actually beforeunload
You can and should handle this event through window.addEventListener() and the beforeunload event. More documentation is available there. (MDN)
I'm just guessing, since the Kendo UI scripts aren't exactly fun to read through, but the 'selected' class is getting applied because a navigation event was started, even though you cancel it; the Kendo script is probably just listening for a successful click. onbeforeunload and beforeunload both happen after the click event has resolved (AFAIK, anyway).
Following worked for me (adding e.stopPropagation):
$('a.k-link').on('click', function (e) {
if (isDirty && !confirm(warnMessage)) {
e.preventDefault();
e.stopPropagation();
} });
or by returning false:
$('a.k-link').on('click', function (e) {
if (isDirty && !confirm(warnMessage)) {
return false;
} });
I have an ajax based application (ie no page 'reloads` when getting new data).
Initially I wanted to find a way to prevent navigation when unsaved data was present on a form.
I came across window.onbeforeunload.
That didn't work when clicking a links (where content is loaded via ajax and pop/push state changes the url).
I added some handling of the a links but need to use the default window.onbeforeunload to cover the standard means of leaving a page (ie manually entering a new URL or using the back/forwards buttons).
The code below works for:
a links
page refresh
manually entering a new url
But is not triggering window.onbeforeunload when using the back button (in Chrome and Firefox).
Is there something awry with the implementation below or is window.onbeforeunload not meant to be triggered when using the back button?
var save_state = true;
// on entering data into an input field, the save button fades in
// and the save_state changes
$(document).on('keypress', '.class1 input', function() {
if (save_state) {
$(".save_button").fadeIn();
save_state = false;
};
// bind the click event to 'a' (overiding normal link behaviour)
$( "a" ).bind( "click", function(e) {
if (save_state == false) {
e.preventDefault();
alert("Save before leaving.");
// stop the other 'a' bound handlers from being triggered
e.stopPropagation();
return;
}
});
// also cover standard actions when user tries to leave page
// (back/forward or entering a new url manually etc)
window.onbeforeunload = function() {
return 'Save before leaving.';
};
});
// when clicking save, fade out the button and revert the save_state
$(document).on('click', '.save_button button', function(e) {
e.preventDefault();
$(this).parent().fadeOut();
save_state = true;
// 'unbind' onbeforeunload
window.onbeforeunload = null;
});
Edit:
After reading this post, I think it is based on the ajax nature of the app:
As long as you stay within your app, because it's a single-page app,
it doesn't by definition unload, so there's no beforeunload event.
So I think I may need to look at other ways to trigger the event on back/forwards buttons.
I looked in to triggering window.unload on popstate but didn't have any luck with that.
I ended up changing the logic so that as soon as changes were made, they were saved in the database.
I was using selectize.js for the form input handling and just added some extra calls to it.
In selectize.js (here):
if ($target.hasClass('create')) {
self.createItem();
} else {
value = $target.attr('data-value');
became:
if ($target.hasClass('create')) {
self.createItem();
$(".saved_message_div").fadeIn(400).delay(2000).fadeOut(400); // new
updateDatabaseFunction(); // new
} else {
value = $target.attr('data-value');
$(".saved_message_div").fadeIn(400).delay(2000).fadeOut(400); // new
updateDatabaseFunction(); // new
AND (here):
while (values.length) {
self.removeItem(values.pop());
}
self.showInput();
became:
while (values.length) {
self.removeItem(values.pop());
}
$(".saved_message_div").fadeIn(400).delay(2000).fadeOut(400); // new
updateDatabaseFunction(); // new
self.showInput();
And in my own script, the prompt for deleting selectize.js items stayed the same:
onDelete: function(values) {
confirm(values.length > 1 ? 'Are you sure you want to remove these ' + values.length + ' items?' : 'Are you sure you want to remove "' + values[0] + '"?');
I want to write Jquery code in master file, so that if there if user changes page and there is any unsaved changes user should get alert.
I got one answer from this: link
However in most solution I will have to write code on all pages. I want it to write only at one place so that everybody dont have to worry to write it in their modules. My code is like:
<script type="text/javascript">
var isChange;
$(document).ready(function () {
$("input[type='text']").change(function () {
isChange = true;
})
});
$(window).unload(function () {
if (isChange) {
alert('Handler for .unload() called.');
}
});
</script>
But everytime i make changes in text boxes .change() event is not firing.
What can be wrong in the code?
EDIT:
I changed .change() to .click and it is fired. i am using jquery 1.4.1..is it because of jquery version that change() is not working?
This is what i am using, Put all this code in a separate JS file and load it in your header file so you will not need to copy this again and again:
var unsaved = false;
$(":input").change(function(){ //triggers change in all input fields including text type
unsaved = true;
});
function unloadPage(){
if(unsaved){
return "You have unsaved changes on this page. Do you want to leave this page and discard your changes or stay on this page?";
}
}
window.onbeforeunload = unloadPage;
EDIT for $ not found:
This error can only be caused by one of three things:
Your JavaScript file is not being properly loaded into your page
You have a botched version of jQuery. This could happen because someone edited the core file, or a plugin may have overwritten the $
variable.
You have JavaScript running before the page is fully loaded, and as such, before jQuery is fully loaded.
Make sure all JS code is being placed in this:
$(document).ready(function () {
//place above code here
});
Edit for a Save/Send/Submit Button Exception
$('#save').click(function() {
unsaved = false;
});
Edit to work with dynamic inputs
// Another way to bind the event
$(window).bind('beforeunload', function() {
if(unsaved){
return "You have unsaved changes on this page. Do you want to leave this page and discard your changes or stay on this page?";
}
});
// Monitor dynamic inputs
$(document).on('change', ':input', function(){ //triggers change in all input fields including text type
unsaved = true;
});
Add the above code in your alert_unsaved_changes.js file.
A version that use serialization of the form :
Execute this code, when dom ready :
// Store form state at page load
var initial_form_state = $('#myform').serialize();
// Store form state after form submit
$('#myform').submit(function(){
initial_form_state = $('#myform').serialize();
});
// Check form changes before leaving the page and warn user if needed
$(window).bind('beforeunload', function(e) {
var form_state = $('#myform').serialize();
if(initial_form_state != form_state){
var message = "You have unsaved changes on this page. Do you want to leave this page and discard your changes or stay on this page?";
e.returnValue = message; // Cross-browser compatibility (src: MDN)
return message;
}
});
If the user change a field then manually rollback, no warn is displayed
change event is fired once the user blurs from input not on every single character inputed.
If you need it to be called every time something is changed (even if focus is still in that input field) you would have to rely on combination of keyup and bunch of events to keep track of pasting/cuting using mouse only.
P.S.
I hope you're aware that your approach to detecting changes isn't the best one? If user input some text, leaves the field and then reverts the changes the script would still alert him about modified text.
you should register events for not only inputs but also textareas, if you mean textarea with text box. You can use keyup for isChange, so that you don't wait for user to blur from this area.
$("input[type='text'], textarea").keyup(function () {
isChange = true;
})
This is really just a different version of #AlphaMale's answer but improved in a few ways:
# Message displayed to user. Depending on browser and if it is a turbolink,
# regular link or user-driven navigation this may or may not display.
msg = "This page is asking you to confirm that you want to leave - data you have entered may not be saved."
# Default state
unsaved = false
# Mark the page as having unsaved content
$(document).on 'change', 'form[method=post]:not([data-remote]) :input', -> unsaved = true
# A new page was loaded via Turbolinks, reset state
$(document).on 'page:change', -> setTimeout (-> unsaved = false), 10
# The user submitted the form (to save) so no need to ask them.
$(document).on 'submit', 'form[method=post]', ->
unsaved = false
return
# Confirm with user if they try to go elsewhere
$(window).bind 'beforeunload', -> return msg if unsaved
# If page about to change via Turbolinks also confirm with user
$(document).on 'page:before-change', (event) ->
event.preventDefault() if unsaved && !confirm msg
This is better in the following ways:
It is coffeescript which IMHO automatically makes it better. :)
It is entirely based on event bubbling so dynamic content is automatically handled (#AlphaMale's update also has this).
It only operates on POST forms as GET forms do not have data we typically want to avoid loosing (i.e. GET forms tend to be search boxes and filtering criteria).
It doesn't need to be bound to a specific button for carrying out the save. Anytime the form is submitted we assume that submission is saving.
It is Turbolinks compatible. If you don't need that just drop the two page: event bindings.
It is designed so that you can just include it with the rest of your JS and your entire site will be protected.
Why not simply bind the event to the change callback?
$(":input").change(function()
{
$(window).unbind('unload').bind('unload',function()
{
alert('unsaved changes on the page');
});
});
As an added bonus, you can use confirm and select the last element that triggered the change event:
$(":input").change(function()
{
$(window).unbind('unload').bind('unload',(function(elem)
{//elem holds reference to changed element
return function(e)
{//get the event object:
e = e || window.event;
if (confirm('unsaved changes on the page\nDo you wish to save them first?'))
{
elem.focus();//select element
return false;//in jQuery this stops the event from completeing
}
}
}($(this)));//passed elem here, I passed it as a jQ object, so elem.focus() works
//pass it as <this>, then you'll have to do $(elem).focus(); or write pure JS
});
If you have some save button, make sure that that unbinds the unload event, though:
$('#save').click(function()
{
$(window).unbind('unload');
//rest of your code here
});
Without jQuery:
var unsaved = false;
document.addEventListener("DOMContentLoaded", function() {
var els = document.querySelectorAll('textarea, input, select');
els.forEach( function(el) {
el.addEventListener('change', function() {
unsaved = true;
});
});
window.addEventListener('beforeunload', function(event) {
if(unsaved){
event.returnValue = "string";
}
});
var forms = document.querySelectorAll('form');
forms.forEach( function(form) {
form.addEventListener('submit', function() {
unsaved = false;
});
});
});
The weird 'string' hack explanation can be found here.
I use $('form').change etc. function to set a dirty bit variable. Not suitable to catch all changes (as per previous answers), but catches all that I'm interested in, in my app.
I've got a form which is being submitted via PHP with 3 submit actions:
Save and Continue
Save and Exit
Exit without Saving
I'd like to trigger an "OnBeforeUnload" alert to display if the user DOES NOT click on any of the form actions to advise them that they're leaving the page, and their changes may not be saved.
I've tried the following code but it seems as though the unbeforeunload is being triggered before my click event. Any suggestions on how best to achieve this?
$buttonpressed = false;
$j(".Actions input").click(function(){
$buttonpressed = true;
});
if(!$buttonpressed){
window.onbeforeunload = function(){
return "Your changes may not be saved.";
}
}
You need to do the check inside the handler, like this:
window.onbeforeunload = function(){
if(!$buttonpressed){
return "Your changes may not be saved.";
}
}
Currently it's binding window.onbeforeunload when your code is run because $buttonpressed is false when it runs...it doesn't matter if it changes later since you already bound the handler. An alternative is to make it a bit simpler, like this:
window.onbeforeunload = function(){
return "Your changes may not be saved.";
}
$j(".Actions input").click(function(){
window.onbeforeunload = null;
});
This just removes the handler on click instead. A more appropriate event to handle other submit cases would be to attach to the submit event, like this:
$j(".myForm").submit(function(){
window.onbeforeunload = null;
});
I have a page with a form that is submittes via ajaxSubmit() (so, without changing the page).
My goal is that, when the user try to change page (or even to close the browser), i ask him if really want to exit the page without sending the form (exactly as gmail does).
Gmail for example do this with a window.confirm-like popup, but if it is possible, i'll like to handle it with custom messages and options.
jQuery have the unload event:
$(window).unload( function () { alert("Bye now!"); } );
but it permits me just to do something before exit the page; i need to 'block' the page exit, if the user click the relative button.
So, how to handle (and cancel) the page-exit event?
try the following. Demo here
<script type="text/javascript">
function unloadPage(){
return "dont leave me this way";
}
window.onbeforeunload = unloadPage;
</script>
It's possible bind the "onbeforeunload" event with jQuery:
$(window).bind('beforeunload', function(e) {
return "ATTENZIONE!!";
});
It works!!