Note that there are some explanatory texts on larger screens.

plurals
  1. POjQuery autopostback problem
    text
    copied!<p>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: </p> <pre><code>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; } } }); }); </code></pre> <p>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?</p> <p>Ok, I modified script slightly, created a hidden field to save dirty state between postbacks, so it looks like this:</p> <pre><code> 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; } } }); </code></pre> <p>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.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload