Monday, October 31, 2011

How to restrict accidential navigation from entry page?(On Before Unload in JavaScript)

One of common scenario is that , if we are entering huge data or important data in particular aspx page there may be a chance that accidentally we click on something which causes to navigate another page. so certainly we will lose entered data. To avoid this we must implement, some concepts. one of the helping concept is explained below.

This must be remedied in some way, if you are creating an application that needs the user to input stuff, especially lengthy articles. One approach is to automate draft saving every a few minutes, the other is to warn the user before he or she either intentionally or inadvertently navigate away from the editor page. You can achieve this by a straightforward snippet of JavaScript:
var warning = false;
window.onbeforeunload = function() {
  if (warning) {
    return 'You have unsaved changes.';
  }
}
The warning variable can be timely altered according to the editing activities by the user. For instance, it is set true if the editing field is changed or does not equal to default value, or if the user triggers the onKeyUp / onChange event of any input fields:
var editor_form = document.getElementById("form_id");
for (var i = 0; i < editor_form.length; i++) {
        editor_form[i].onchange = function() {
               warning = true;
        }
}
This snippet must be put at the end of the page. Also, to avoid the warning when you press the form submit button, add this snippet after that:
document.getElementById("submit_button_id").onclick = function() {
    warning = false;
}

Better avoid anchor tag or link button in the page unless it is important.


No comments:

Post a Comment