javascript - Detecting form changes on beforeunload? - Stack Overflow

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

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

/

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.';
    }

});​

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

http://jsfiddle/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.';
    }

});​

Share Improve this question asked Sep 26, 2012 at 18:40 Sarah JeanSarah Jean 6482 gold badges11 silver badges19 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 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/M9tnP/20/

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.)

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744355794a4570224.html

相关推荐

  • javascript - Detecting form changes on beforeunload? - Stack Overflow

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

    7天前
    50

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信