In more complicated applications, it often makes sense to warn users if they try to navigate away from a form without saving the information. For example, in NutrientNet, I have a tool that calculates nutrient credits that spans several tabs, each with a separate form. Users may inadvertently click one of the tabs before they have saved the data on the form.
To prevent this from happening, we can attach an onchange event to every form element that activates a window.onbeforeunload event if the form is not submitted. JQuery makes this easier, by allowing us to attach the event to every input element of a form when the page loads. That way, if we add another element to the form later, we don't have to worry about accidentally forgetting to add the onchange event.
First, let's take a look at the javascript code that controls the onbeforeunload event:
function setConfirmUnload(on) {
window.onbeforeunload = (on) ? unloadMessage : null;
}
function unloadMessage() {
return 'You have entered new data on this page. If you navigate away from this page without first saving your data, the changes will be lost.';
}The setConfirmUnload() function turns on or off the onbeforeunload event. The unloadMessage() function just returns the message that we want to display.
Next, we add the following JQuery code to the page with the form that we would like to control:
$(document).ready(function() {
$(':input',document.myForm).bind("change", function() { setConfirmUnload(true); }); // Prevent accidental navigation away
});'myForm' should be the name of the form that you want to use.
Finally, to prevent the warning from appearing when we click the submit button, I usually add "setConfirmUnload(false);" to the end of the form validation function that I use for my form.
Happy coding!
Binding change event to all html elements using Jquery
Hey -
I believe this is very elegant way of warning user about the loss of data. Do you by any chance hold a complete working example where all the html elements are binded to the change event and would trigger the prompt when we navigate away from the current page (only if any changes were made)
Thank You,
Jagadeesh