Current streak: 143 days / 326 commits - What's this?

Using JQuery to Warn Users About Losing Data When Navigating Away from Form

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.

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!


---
More posts:
Python Character Decoding FTP Files
CSRF Protection in Angular and Flask
100 commits in 100 days: Recap
Android REST Client Implementation: REST Method
Detecting Android ViewPager Tab Changes