Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trigger dialog with JS before leaving current page

Tags:

javascript

When a user have changed something in a form, then clicks on any link that will direct him to another page, I'd like to trigger a popup with a "Would you like to Save before leaving?" option.

How can I do this?

like image 772
olemarius Avatar asked Feb 05 '09 06:02

olemarius


1 Answers

Example:

 <script type="text/javascript">
     var shouldConfirm = false;
     window.onbeforeunload = function() {
         if(shouldConfirm) {
             return "You have made unsaved changes. Would you still like to leave this page?";
         }
     }
 </script>

 <input id="FullName" type="text" />
 <script type="text/javascript">
     document.getElementById('FullName').onchange = function() {
         shouldConfirm = true;
     }
 </script>

There's a full article at 4GuysFromRolla.com.

like image 64
EndangeredMassa Avatar answered Sep 19 '22 13:09

EndangeredMassa