Thursday, February 7, 2008

Confirmation before leaving a page

What if the user didn't hit save before navigating to another page, what will happen then?

Below is a solution for this commonly asked question, hope it will help.
-------------------------------------------------------------------------------------

Add the following javascript to your page
<script type="text/javascript">
var needToConfirm = false;//Flag to check if save button is hit or changes has happened
window.onbeforeunload = confirmExit;//calling confirmExit function onbefore unload
function confirmExit()
{
if (needToConfirm==true)//Save button was not hit or changes to the page has happened
return "--------------------------------------------------\n" +
"Warning:\n" +
"If you have made any changes to this page without clicking the Save button, your changes will be lost\n" +
"--------------------------------------------------";
}
</script>

-Add some controls to your page

-Setting needToConfirm flag to true if any changes happened(code behind)
private void AddAttributes()
{
txtName.Attributes.Add("onkeyup", "needToConfirm=true");
txtEmail.Attributes.Add("onkeyup", "needToConfirm=true");
txtAddress.Attributes.Add("onkeyup", "needToConfirm=true");
ddlTests.Attributes.Add("onchange", "needToConfirm=true");
}
-----------------------------------------------------------------------------------
Now Open your page and write anything in any textbox, donot hit save and close your browser.

Confirmation message will appear asking you if you really want to leave the page or not

HTH

5 comments:

Anonymous said...

Bilal, you saved my life. I am thankfull because all my clients need that alert.

Anonymous said...

Very good article.

Anonymous said...

Im glad to here that samer, good luck :)

Regards

Anonymous said...

your site is a very good idea.I really appreciate your spirit of sharing the new technologies in .net.Wainting for everything new ;)

Anonymous said...

This is exactly what i was looking for. thnx.
--M Vaqqas