javascript onbeforeunload event

Hi All,

I am a new customer to experts-exchange and this is my first question.
I am also fairly new to javascript.

I have a requirement to capture any changes made to a form when a user clicks the browers BACK or FORWARD button and show a warning message.If no edits are made in the form then the warning message should not appear
Can I do it using javascript?
If I can do it can any one tell me what are the events that I have to use?
I have searched google a little bit and undrestand that onbeforeunload does this functionality.
But how would i recognise whether any changes are made to form data in the onbeforeunload event.

Any help is gretly appreciated.

Thank you
Raj
raju_suryaAsked:
Who is Participating?
 
kadabaConnect With a Mentor Commented:
You might have to use onchange event on the form fields to record the change probably have flag and then use the above syntax.... I mean roughly you could do this way..

<html>
<head>
<title>Capture Changed fields</title>
<script type="text/javascript">
function last_chance() 
{	
	if(isEdited)
	{	
		return "You seem to have edited some information, Are you sure you want to leave?";
	}
}

var isEdited = false;
function captureEdit(){
	isEdited = true;
}

window.onbeforeunload = last_chance;
</script>
</head>
<body>
Name: <input type="text" id="name" value="EE" onchange="captureEdit();">
<br>
Email: <input type="text" id="email" value="ee@ee.com" onchange="captureEdit();">
</body>
</html>

Open in new window

0
 
pavlejovanovCommented:
in .Net code
<script language="javascript" type="text/javascript">
window.onunload = function() {
            PageMethods.SomeFunction();
        }
</script>

in C# code

[WebMethod]
public static void SomeFunction()
{
        //Some code
}

you also must have ScriptManagerr in page
0
 
BadotzConnect With a Mentor Commented:
You don't have to use .NET:


<script type="text/javascript">

function last_chance() {
	return "Are you sure you want to leave?";
}

window.onbeforeunload = last_chance;

</script>

Open in new window

0
 
mickey159Commented:
Try this:
<script language="JavaScript">
  window.onbeforeunload = confirmExit;
  function confirmExit()
  {
    return "You have attempted to leave this page.  If you have made any changes to the fields without submitting, your changes will be lost.  Are you sure you want to exit this page?";
  }
</script>
0
 
BadotzCommented:
mickey159: Your script tag is outdated ("language=" should be "type="); your function comes AFTER it is referenced (possibly inconsequential); your example adds nothing new (except the prompt, of course, but otherwise...).
0
All Courses

From novice to tech pro — start learning today.