0

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>
Marcus
  • 4,400
  • 13
  • 48
  • 64

4 Answers4

2

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

xdazz
  • 158,678
  • 38
  • 247
  • 274
0

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

Geek Num 88
  • 5,264
  • 2
  • 22
  • 35
  • Sorry - that just tells you what the problem is - not a solution. Try and set a variable at the top of the beforeunload function() and if it is changed by the $.each function then return otherwise nothing – Geek Num 88 Oct 25 '12 at 07:35
0

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.

Community
  • 1
  • 1
Roman
  • 504
  • 4
  • 10
-1

Maybe you should use

return confirm('Are you sure you want to leave?');
Mihai Matei
  • 24,166
  • 5
  • 32
  • 50