4

How do I let users know that "there are changes left to be saved on the form if they try to close the browser window?"
I have a form with couple of fields, Now if the user changes some of the fields and clicks on Close button on the browser window, my script should alert him of unsaved changes. How do I implement this? I have put in basic form validation but can't seem to think of a solution for window.close() event. Any sample links would be helpful.

t0mcat
  • 5,511
  • 19
  • 45
  • 58
  • possible duplicate of [What is the best way to track changes in a form via javascript?](http://stackoverflow.com/questions/194101/what-is-the-best-way-to-track-changes-in-a-form-via-javascript) – Kon Jun 02 '11 at 01:01
  • Thanks for the link Kon. It'll help a lot in implementing my solution :) – t0mcat Jun 02 '11 at 01:13
  • But given solution is using jQuery which makes it lot easier. I have to implement this using standard Javascript :( – t0mcat Jun 02 '11 at 01:15
  • Why do you "have" to? jQuery is JavaScript, it's not some new language. It's just a simple JavaScript library. – Kon Jun 02 '11 at 12:44
  • I can either do this in plain javascript, Dojo or ExtJS only. Thats the standard they follow here. – t0mcat Jun 02 '11 at 13:01
  • Are you not allowed to add any third-party .js files to help you code? If not, get a new job. :) – Kon Jun 02 '11 at 13:14
  • unfortunately no :-( lol – t0mcat Jun 02 '11 at 14:04

4 Answers4

1

Well you could use the body onbeforeunload or onunload.

<body onBeforeUnload="return(confirm('unsaved stuff'))">

Never used a return to stop a page unload before but it should work.

Update:

In the header of the web page to make it a global var:

<script type="text/javascript">
var formData = [];
function saveForm(){
    var data = [];
    for(var index = 1; index <= 3; index++){
        data [index - 1] = document.getElementById("textfield_" + index).value;
    }
    return(data);
}

function unsavedData(){
    var newFormData = saveForm();
    for(var index = 0; index < 2; index++){
        if(formData[index] != newFormData[index]){
            return(confirm("Unsaved data, do you really want to exit?"));
        }
    }
    return(true);
}
</script>

In the body(of course):

<body onBeforeUnload="return(unsavedData())">
...
<form ... onSubmit="formData = saveForm()">
<input type="text" id="textfield_1">
<input type="text" id="textfield_2">
<input type="text" id="textfield_3">
/*form submit button*/
</form>
Jonathon
  • 2,571
  • 5
  • 28
  • 49
  • Hi Jonathon, thanks for the reply. Whats the best way to track if user made any changes? What I mean is lets say there is a TextField "Name" populated with data "Mark", now user first backspaced the whole "Mark" and then again retyped it. Can this kind of behavior be detected? – t0mcat Jun 02 '11 at 01:12
  • Well if you saved value of the last saved form values then just compared them: `
    ` `function saveForm(){for(){formData[i] = document.getElementById("textField_" + i).value; /*formData is a global variable*/}}` Then all you would have to do is compare on unload `if(formData[i] == newFormData[i]){return(confirm("unsaved data"));} /*Note I did nto show how to get newFormData but it is easy*/`
    – Jonathon Jun 02 '11 at 02:25
  • If you need a full example I could add it to my answer. – Jonathon Jun 02 '11 at 02:27
  • would be helpful if you can :-) – t0mcat Jun 02 '11 at 02:39
0

Equivalent, but in JavaScript you could do something like:

if ( undefined !== window.onbeforeunload )
{
    window.onbeforeunload = function ()
    {
        var f = window.onbeforeunload;
        var ret = f();
        if (ret)
        {
            return doValidation();
        } else
        {
            return false;
        }
    };
} else
{
    window.onbeforeunload = function ()
    {
        return doValidation();
    };
}

where doValidation() is your custom validation function.

Christopher
  • 1,723
  • 1
  • 18
  • 31
  • Christopher, Thanks a lot. I am sorry I am new to this. So I can hook doValidation() with an onChange event for all the fields on the page? – t0mcat Jun 02 '11 at 01:28
  • Yes and no. One way to do this is through jQuery (remember though, it's just a convenience extension for JavaScript). Add a 'validateMe' css class to every form element you wish to scrutinize and add a change event to each element `$('.validateMe')` gets you all of them. From there, you need to set some persistent variable (global variable, a cookie, client database) that somethingHasChanged = true. Your doValidation() function then looks for that flag and throws whatever action is appropriate. – Christopher Jun 02 '11 at 01:34
  • Thanks for the explanation. jQuery isnt supported here. I am free to use Dojo. Does Dojo has something like $('.validateMe')? – t0mcat Jun 02 '11 at 01:49
0

You can't prevent a user from closing a window (that would mean a malicious script could do that as well, making it a huge security vulnerability).

That being said, you can ask if the user wants to save his/ her changes before actually leaving the page. You would need onBeforeUnload (set the attribute in HTML or use javascript) to call a script. This is what that script could look like:

function beforeClose () {

    if (formChanged) {

        var chk = confirm('Do you want to save your changes before you go?');
        if (chk) {

             // Code (AJAX) that will send/ store the data)

         }
     }
}

In this function I invented a variable called 'formChanged'. The most sensible way to do this is to track whether a user has changed things while on the page (by adding the onChange attribute to the form fields that will set the formChanged variable to true). The linked post in your question's first comment shows you a jQuery script that will check for changes, if you want to use that.

Battle_707
  • 708
  • 5
  • 15
  • Hi Battle, Thanks for explaining your solution. Helped a lot. I will also edit my question "I dont want to restrict browser close, just a confirm dialog for unsaved changes." – t0mcat Jun 02 '11 at 01:34
0

You can use the beforeunload even to run a function that checks the default values of successful form controls with their current value. If there are any differences, prompt the user. Otherwise, do nothing.

RobG
  • 142,382
  • 31
  • 172
  • 209