Possible Duplicate:
Detecting Unsaved Changes using JavaScript
My Web application has 3 web forms ,I implemented the validations in my webpage.I want to implement is开发者_如何转开发dirty functionality in my web application.I want to pop up a message box in my webpage when a user clicks on sign out(which is a loginstatus control) if there any changes made to the form.
Environment: Asp.net VS2008 c#
This could be easily done with jquery and the onbeforeunload
event. Using the .serialize()
function you could calculate the state of the form on the returned string once when the page loads and then in the onbeforeunload
event. Then compare the two values and if they are different something indeed has changed in the form.
Example:
<%@ Page Language="C#" %>
<!DOCTYPE html>
<html>
<head id="Head1" runat="server">
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"></script>
<script type="text/javascript">
var data = '';
$(function () {
data = $('form').serialize();
});
window.onbeforeunload = function () {
if ($('form').serialize() !== data) {
return 'You have unsaved changes. Are you sure you want to navigate away?';
}
};
</script>
</head>
<body>
<form id="Form1" runat="server">
<asp:TextBox ID="FirstName" runat="server" />
<asp:TextBox ID="LastName" runat="server" TextMode="MultiLine" />
<asp:CheckBox ID="Chk" runat="server" />
<asp:HyperLink ID="Link" runat="server" Text="Go to Google" NavigateUrl="http://www.google.com" />
</form>
</body>
</html>
Some other techniques (like the one presented in the duplicate question that was voted to close for your question) involve in subscribing for the .change()
event of the input elements but they are less reliable as the user could for example type abc
in some input field and then delete it and if you used this technique the form would be considered as dirty although no value actually changed.
You can easily setup a popup/modal window to show-up when the user tries to leave a form/page. Here is a quick pure javascript example, that shows a message when you try to leave a page.
<body onunload="if (confirm('Save form ?')) { SaveFormMethod(); }">
If you need a better example, you should provide more details and show us your code.
Please take a look at this answer and see if it helps
精彩评论