Preventing the User from Navigating Away from a Dirty Page

A bug popped up in testing today in some code a wrote a few months ago to prevent our users from navigating away from a modified page. When I did my initial testing, I neglected to test the case where the user makes a change to a single control and then clicks the back button without changing focus off that control. Here is my updated code. I am sure there are better ways to do this, but this works as an initial pass.

var isDirty = false;
window.onbeforeunload = checkIsDirty;
 
$(document).ready(function() {
    $(".form input[type='text']").keypress(function() { isDirty = true; });
    $(".form input[type='text']").change(function() { isDirty = true; });
    $(".form input[type='checkbox']").click(function() { isDirty = true; });
    $(".form input[type='radio']").click(function() { isDirty = true; });
    $(".form textarea").keypress(function() { isDirty = true; });
});
 
function checkIsDirty() {
    if (isDirty == true) {
	return 'The information on this page has been modified.';
    }
}
<script src="/js/jquery-1.3.2.min.js" type="text/javascript"></script>
<script src="/js/isdirty.js" type="text/javascript"></script>
<div id="form1" class="form">
     Enter Text Here:
     <input type="text" id="TextBox1" value="" />
     <input type="button" id="Button1" value="Submit" onclick="isDirty=false;" />
</div>

This works directly against the html inputs, or with the ASP.NET server controls, like asp:TextBox, asp:Checkbox, etc.

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Reddit
  • DotNetKicks
  • Technorati
  • TwitThis

Leave a Reply