2

This has already been asked, I know, but I don't understand why this isn't working for me.

http://jsfiddle.net/M9tnP/16/

Trying to detect form changes, and if the user tries to navigate away, I want them to confirm that they will lose their changes...

var dirty = false;
$("form#add_item :input").change(function() {
    dirty = true;
});

$("window").on('beforeunload', function() {
    if (dirty) {
        return 'You have unsaved changes! If you leave this page, your changes will be lost.';
    }

});​

Sarah Jean
  • 648
  • 2
  • 10
  • 19

2 Answers2

8

You need to set the event handler for onbeforeunload directly on the window object:

var dirty = false;
$("form#add_item :input").change(function() {
    //alert("form changed!")
    dirty = true;
});

window.onbeforeunload = function() {
    if (dirty) {
        return 'You have unsaved changes! If you leave this page, your changes will be lost.';
    }
};​

Working example: http://jsfiddle.net/M9tnP/20/

Elliot B.
  • 17,060
  • 10
  • 80
  • 101
  • Did you edit the text box first? I'm using Chrome 21 as well. – Elliot B. Sep 26 '12 at 18:46
  • 1
    And when you click 'Leave Page' remember that it re-directs you to your old jsFiddle revision. You need to make sure you're viewing revision 18 http://jsfiddle.net/M9tnP/18/ – Elliot B. Sep 26 '12 at 18:48
  • This is not true: "You need to set the event handler for onbeforeunload directly on the window object". `$(window).on('beforeunload', function() {...})` (without the quotes) works fine, and is preferable to assigning `window.onbeforeonload`, because now several can subscribe to the `beforeonload` event! – Peter V. Mørch Aug 08 '13 at 21:15
  • A minor note - perhaps you don't care: Beware that [beforeunload doesn't work on iOS](http://stackoverflow.com/questions/3239834/window-onbeforeunload-not-working-on-the-ipad). – Peter V. Mørch Aug 08 '13 at 21:17
0

You need:

$(window).on('beforeunload', function() {...})

, not:

$("window").on('beforeunload', function() {...})

(no quotes around window). $(window) wraps the window javascript variable inside a jQuery object, where $("window") selects all <window> tags on the page, of which there are exactly 0.

(Most of the time. In fact you can do $('body').append('<window></window>'), and then $("window") matches that new tag - but don't do that.)

Peter V. Mørch
  • 13,830
  • 8
  • 69
  • 103