I am working on ASP.NET 3.5 website project and using jQuery to warn users if they modified a page and attempt to leave the page without saving, so doing something like this:
var warning = "Please save changes you made.";
var isDirty = false;
$(document).ready(function()
{
$('input:text,input:checkbox,input:radio').bind('change', function()
{
isDirty = true;
$('input[type=submit]').bind('click', function(e)
{
isDirty = false;
});
window.onbeforeunload = function()
{
if (isDirty)
{
return warning;
}
}
});
});
It works fine, but when I make changes on a page and then select a different item in a dropdown on a page, which causes a post back, I get a warning, which I should not.Is it feasible to implement this feature in jQuery, i.e. give warning on really leaving page, but ignoring postbacks, and what changes to the script I need to make in that case?
Ok, I modified script slightly, created a hidden field to save dirty state between postbacks, so it looks like this:
var warn_on_unload = "Leaving this page will cause any unsaved data to be lost.";
var previouslyDirty = false;
var isDirty = false;
$(window).load(function()
{
previouslyDirty = $('#dirtyFlag').val() == '1';
});
$(window).unload(function()
{
$('#dirtyFlag').val(previouslyDirty ? '1' : '0');
});
$(document).ready(function()
{
$('input:checkbox,input:radio').one('change', function()
{
isDirty = true;
previouslyDirty = true;
});
$('input:text, textarea').keydown(function()
{
isDirty = true;
previouslyDirty = true;
});
$('form').submit(function(e)
{
isDirty = false;
previouslyDirty = false;
});
$('select').bind('change', function(e)
{
isDirty = false;
previouslyDirty = true;
});
window.onbeforeunload = function()
{
if (isDirty || previouslyDirty)
{
return warn_on_unload;
}
}
});
Still behaves incorrectly after non-submitting postbacks, which it should allow them without a warning, but saving dirty state, so if I change dropdown, no problem on postback , but if I try to leave page after that, should get a warning. Also, need to take of care of submitting postbacks, i.e. saving buttons, obviously allowing them and clearing all dirty flags previously set.