Search code examples
jqueryonbeforeunload

jquery beforeunload does not display message


The jsfiddle for this is at http://jsfiddle.net/whDm6/18/

If I uncomment the Alert in the following code, change a form value, and refresh the page, it displays an alert. So I know the code is executing up to that point. But if I leave the Alert commented out it does not display the beforeunload box like I expect it to.

I have tried using bind and also using a basic window.onbeforeunload = function() {} without binding it with Jquery but none of those worked.

Using Jquery 1.8.2

var currentUlValues = {};
currentUlValues['input1'] = "red";
currentUlValues['input2'] = "blue";
needToConfirm = true;

$(window).on('beforeunload', function(){
    if (needToConfirm) {
        $.each(currentUlValues, function(key, value) {
            var elem = $("#"+key).val();
            if (typeof elem !== 'undefined') {
                if (elem != currentUlValues[key]) {
                    //alert(elem + " - " + currentUlValues[key]);
                    return 'Are you sure you want to leave?';
                }
            }
        });
    }
});

HTML Form

<form>
    <input id="input1" name="input1" type="text" value="red" />
    <input id="input2" name="input2" type="text" value="blue" />
</form>

Solution

  • You are return form the callback function of .each, which is in wrong scope, you should return the string outside it.

    The working demo:

    $(window).on('beforeunload', function(){
        var is_return = false;
        if (needToConfirm) {
            $.each(currentUlValues, function(key, value) {
                var elem = $("#"+key).val();
                if (typeof elem !== 'undefined') {
                    if (elem != currentUlValues[key]) {
                        is_return = true;
                        // here return false is to stop the iterate
                        return false;
                    }
                }
            });
            if (is_return) {
                return 'Are you sure you want to leave?';
            }
        }
    });