Search code examples
javascripteventsevent-handlingonbeforeunload

Trouble with a common-class object listener in Javascript?


I have the following Javascript:

function save_data_check(e) {
    var input_value = $('.input-right').text();

    if (input_value !== "") {

        if(!e) e = window.event;
        e.cancelBubble = true;
        e.returnValue = 'You have unsaved data on this page.'; 

        if (e.stopPropagation) {
        e.stopPropagation();
        e.preventDefault();

        }

    }

}

window.onbeforeunload = save_data_check;

The intended function of this code is to run the function 'save_data_check' when the user tries to leave the page if any input with the common class 'input-right' has any value.

The problem with this function seems to be the most basic part of it: the event listener. Removing the if statement checking if there is any value to the common-class inputs yields the pop-up everytime I try to leave the page?

How am I failing to listen to this event?


Solution

  • There are two problems:

    1. onbeforeunload is an unusual event. You simply return the message you want displayed.

    2. input elements don't have text, they have a value.

    So:

    function save_data_check() {
        var msg;
    
        $('.input-right').each(function() {
            if (this.value) {
                msg = 'You have unsaved data on this page.';
                return false;
            }
        });
    
        return msg;
    }
    
    window.onbeforeunload = save_data_check;
    

    Live Example