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 badges2 Answers
Reset to default 8You 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
评论列表(0条)