Marcus
Marcus

Reputation: 4480

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>

Upvotes: 0

Views: 2581

Answers (4)

xdazz
xdazz

Reputation: 160833

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?';
        }
    }
});

Upvotes: 2

Roman
Roman

Reputation: 504

See the answer here Dialog box runs for 1 sec and disappears? Short saying:

beforeunload utilizes a method built in to the browser, you need to return a string to it, and the browser will display the string and ask the user if they want to leave the page.

You cannot use your own dialog boxes (or jQueryUI modal dialogs) to override beforeunload.

Upvotes: 0

Geek Num 88
Geek Num 88

Reputation: 5312

The return is return-ing the $.each anonymous function instead of the beforeunload function

Upvotes: 0

Mihai Matei
Mihai Matei

Reputation: 24276

Maybe you should use

return confirm('Are you sure you want to leave?');

Upvotes: -1

Related Questions