Check textarea with JavaScript before closing a window

This is a JavaScript program to check if a textarea (with the id note) has been altered and send up a confirmation dialogue when the page is deleted, if the textarea has been changed.

The HTML part looks like this:

<form onsubmit="form_submit ()">
<textarea name='note'>
</textarea>
</form>

The JavaScript looks like this:

var check_on_unload = true;

function form_submit ()
{
    check_on_unload = false;
    input = note_value ();
    if (input == initial_input) {
//        alert ("not changed");
        return false;
    }
}

/* Make sure to confirm before deleting the window. */

window.onbeforeunload = function ()
{
    input = note_value ();
    if (input != initial_input) {
        alert ("has changed");
        if (check_on_unload) {
            return "Have you saved the log?";
        }
    }
}

var initial_input;

function note_value ()
{
    var note = document.getElementById ('note');
    return note.value;
}

function save_input ()
{
    initial_input = note_value ();
//    alert (initial_input);
}
save_input ();

(download)


Copyright © Ben Bullock 2009-2019. All rights reserved. For comments, questions, and corrections, please email Ben Bullock (benkasminbullock@gmail.com) or use the discussion group at Google Groups. / Privacy / Disclaimer