Dirty, Dirty, Dirty… Implementing IsDirty with JavaScript
Sometimes when a user is editing a page, you want to let them know that if they click on a link or a section of the main navigation that they will lose their changes.
Here's a quick walk through on an IsDirty implementation I did with jQuery and ASP.NET.
Add this hidden field somewhere on your page
<input type="hidden" id="dirty" value="" />
Here is the JavaScript that will manipulate the value.
<script src="js/jquery-1.2.3.min.js" type="text/javascript"></script> <script type="text/javascript"> window.onbeforeunload = checkExit; function confirmExit() { // this value will be return as a part of the confirmation message return "If you have made any changes to the fields without clicking the Save button, your changes will be lost."; } function checkExit() { if ($("#dirty").val() == "true") { return confirmExit(); } } function setDirty(changeVal) { $("#dirty").val(changeVal); } function confirmAndClean(msg) { setDirty(false); return confirm(msg); }
</script>
The only thing that remains it to make sure that you call these JavaScript client functions in the appropriate places.
With ASP.NET I would do something like this:
ddlCategoryPage.Attributes.Add("onclick", "setDirty(true);"); txtTitle.Attributes.Add("onkeyup", "setDirty(true);"); btnSavePage.Attributes.Add("onclick", "setDirty(false);"); btnCancelPage.Attributes.Add("onclick", "return confirmAndClean('Any changes you have made will be lost. Are you sure you want to cancel?')");
When I save the page I set the dirty var false so that the user is not prompted. When the dropdown or title on the page is edited I set the dirty var to true. The cancel button calls a function that clears the dirty var and displays a custom confirmation box.
With standard HTML I could call the functions like this:
<input type="text" onkeyup="setDirty(true)" /> <input type="submit" value="Save" onclick="setDirty(false)" />
Seems to work like a charm so far. Hope this helps you out. If you have questions, do not be afraid to shoot me an email or post a comment.















4 Comments, Comment or Ping
ven palani
HI I'm trying to implement dirtychecking logic. I tried the above code and it doesnt work for me. Is js/jquery-1.2.3.min.js a seperate Javascript file . how to download. I copied the rest of code just given below the above link. But not working. Please help me with this.
thanks
v.palani
Aug 11th, 2008
cwpollock
@van palani
You can download the latest version of jquery from their web site: http://docs.jquery.com/Downloading_jQuery
You may need to change the JavaScript include to be the same as the latest file that you download.
Aug 11th, 2008
Mahesh
How to check Dirty read in Fck editor in asp.net.
Mar 29th, 2011
MAHESH
please reply ssoon, for fck editor dirty form check
Apr 19th, 2011
Reply to “Dirty, Dirty, Dirty… Implementing IsDirty with JavaScript”