sim.plified.com

Chris Pollock

Chris Pollock - web developer (PHP/mySQL & ASP.NET)
undivided… my thoughts on world, family, church, business, technology and Jesus Christ (all in all)

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.

Technorati Tags: ,,

No Comments, Comment or Ping

Reply to “Dirty, Dirty, Dirty… Implementing IsDirty with JavaScript”

My Pictures

CIMG6647CIMG6646CIMG6643CIMG6641CIMG6640CIMG6638CIMG6637CIMG6635CIMG6632CIMG6629

Chris Pollock

Web Developer - proficient in both PHP and ASP.NET.
Rochester, New York

View my web developement site.

View Chris Pollock's LinkedIn profile

My Pictures

CIMG6647CIMG6646CIMG6643CIMG6641CIMG6640CIMG6638CIMG6637CIMG6635CIMG6632CIMG6629