42

The following code executes a warning if you change data on the page and then leave the page. I want that - except when the user presses the save button.

This is the jquery code:

$(document).ready(function() {
  formmodified=0;
    $('form *').change(function(){
        formmodified=1;
    });
  window.onbeforeunload = confirmExit;
    function confirmExit() {
      if (formmodified == 1) {
          return "New information not saved. Do you wish to leave the page?";
      }
  }
});

This is the button that saves the data:

<input class="btn-primary" name="commit" type="submit" value="Save Material">

UPDATE Thanks tymeJV !!!!!!!

In case someone else need it, this works:

$(document).ready(function() {
    formmodified=0;
    $('form *').change(function(){
        formmodified=1;
    });
    window.onbeforeunload = confirmExit;
    function confirmExit() {
        if (formmodified == 1) {
            return "New information not saved. Do you wish to leave the page?";
        }
    }
    $("input[name='commit']").click(function() {
        formmodified = 0;
    });
});
Reddirt
  • 5,913
  • 9
  • 48
  • 126
  • 2
    Is 'formmodified' just used for the duration of the page? And not passed on? If so, then just set it to 0 onclick of the Save button, or onsubmit of the form. – MasNotsram May 01 '13 at 16:24
  • Not sure I understand, you want a warning that information is NOT saved when you click the save button? – Colin Bacon May 01 '13 at 16:26
  • @ColinBacon I believe he want's it so that if he click's the save button, don't show the warning at the end about saving. – tymeJV May 01 '13 at 16:27
  • @tymeJV Ah ok, thanks for clearing that up :) – Colin Bacon May 01 '13 at 16:29
  • I want a warning if the type anything into the form, then leave the page without clicking the save button. – Reddirt May 01 '13 at 16:42
  • Possible duplicate of [Warn user before leaving web page with unsaved changes](http://stackoverflow.com/questions/7317273/warn-user-before-leaving-web-page-with-unsaved-changes) – Wasim A. Jan 24 '16 at 01:56
  • how can usend parameters throug confirmExit function as arguments? – Alberto Acuña Aug 30 '17 at 11:15
  • This is great - but as of now ( Nov '17) Firefox is not showing this message, but rather a generic message. Anyone have an idea on how to show the customized prompt text? – kneidels Nov 26 '17 at 09:37

7 Answers7

23

Given your save button info:

<input class="btn-primary" name="commit" type="submit" value="Save Material">

You can set the value of formmodified

$("input[name='commit']").click(function() {
    formmodified = 0;
});

Your check at the end shouldn't be triggered now

tymeJV
  • 103,943
  • 14
  • 161
  • 157
  • Works like a charm. And we actually don't need the last line "Are you sure you want to leave the page?" as this appears to be integral to the browser's (at least Chrome's) confirmation prompt. – cbmtrx May 04 '15 at 01:17
  • Hmm, maybe I spoke too soon, @tymeJV. It appears that--on Chrome, at least--the `window.onbeforeunload` calls the `confirmExit()` function before the `input.commit` button's click is registered. So it pops the alert even on form submission. – cbmtrx May 05 '15 at 13:18
  • The solution is to use `submit` instead of `click`: `$('form#id').submit(function() { formmodified = 0; });` @Reddirt @tymeJV – cbmtrx May 05 '15 at 13:25
  • @cbmtrx I have a small issue. When i edit a text box and directly click on refresh button in the browser, confirmation is not shown. Only after clicking outside the input box fires .change event for that input listener – kishorer747 Feb 29 '16 at 05:27
  • 1
    @kishorer747 Looks like the DOM is only updated after the edited form field is blurred. You might have to use a jquery event listener to update the DOM for any individual change to a form field. – cbmtrx Mar 01 '16 at 12:08
  • Instead of trying to hook 'onbeforeunload'...Mouseleave may be the answer. $('#totalpage').mouseleave. – Robert Koernke Apr 24 '19 at 18:52
9
$('#form').data('serialize',$('#form').serialize()); // On load save form current state

$(window).bind('beforeunload', function(e){
    if($('#form').serialize()!=$('#form').data('serialize'))return true;
    else e=null; // i.e; if form state change show box not.
});

You can Google JQuery Form Serialize function, this will collect all form inputs and save it in array. I guess this explain is enough :)

Wasim A.
  • 9,660
  • 22
  • 90
  • 120
5

This is not an exact answer to the above question but for reference for those who are searching for a solution to the problem 'notify users about unsaved form changes' like I was, I'd like to recommend the jQuery plugin AreYouSure. This very lightweight plugin handles all the nuts and bolds like reverted form changes, clicking the form reset button, adding/removing form fields etc. without any further fiddling.

wedi
  • 1,332
  • 1
  • 13
  • 28
1

Your warning will not be presented until blur, which isn't going to be 100% foolproof. Change the following lines to make it air tight:

$('form *').change(function () {

to

$('form *').on('change input', function () {
Pika Supports Ukraine
  • 3,612
  • 10
  • 26
  • 42
JasonM
  • 86
  • 5
0

If you want to prevent the page from leaving when a link is clicked, you can bind to the beforeunload event and pass e in:

$(document).ready(function() {
    var modified = false;
    $(window).bind('beforeunload', function(e){
        if (modified) {
            $.confirm({
                'title' : 'Did You Save Your Changes?',
                'message'   : 'It seems as if you have made changes but didn\'t click Save.\nAre you sure you want to leave the page?',
                'buttons'   : {
                    'OK'    : {
                        'class' : 'gray',
                        'action': function(){}  // Nothing to do in this case. This can be omitted if you prefer.
                    }
                })
            }
            e.preventDefault();
        }
    });
});    
  • Doest not work for me: clicking on any link or hitting reload in the browser, just open / reload the page. – Fabien Jun 08 '16 at 08:29
  • 1
    From https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload: "Since 25 May 2011, the HTML5 specification states that calls to window.alert(), window.confirm(), and window.prompt() methods may be ignored during this event. See the HTML5 specification for more details." – dieend Jun 09 '16 at 06:52
0

First, you need to get the value of your inputs if the user has done any changes to the form. so i came up with this answer:

    document.querySelector('.send').addEventListener("click", function(){
        window.btn_clicked = true;
    });
    window.onbeforeunload = function(){
       if(!window.btn_clicked){
        var bla = $('#lot_t').val(); // getting the value of input
          if(!bla == ''){    //checking if it is not null
            return 'Are you sure to leave this page?';
          }
}


    };
curiosity
  • 834
  • 8
  • 20
0

My code, change some things from the example because it did not work in my case

  $(document).ready(function() {
        let formmodified = 0;
        $('#id_form').change(function(){
            formmodified=1;
            console.log(formmodified)
        });
        $('#id_buttom').click(function() {
            formmodified = 0;
            console.log(formmodified)
        });
        window.onbeforeunload = confirmExit;
        function confirmExit() {
            console.log('s');
            if (formmodified == 1) {
                return "Exit?";
            }
        }
    });
gerMdz
  • 71
  • 1
  • 5