1

I want to detect when user is leaving browser however I need to check on some condition, the script below skips the if(false) and always prompts for request regardless of returning true or false.

How can I let it check condition before prompting?

<html>
<head>
    <script type="text/javascript" src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
</head>

<body>

<script type="text/javascript">
    $(document).ready(function ()
    {
        $(window).bind('beforeunload', function () {
            if (false)
                return "Are you sure? Your changes will be lost!";
            else
                return false; // or true doesn't matter
        });
    });
</script>

</body>
</html>
saimiris_devel
  • 667
  • 1
  • 6
  • 19
  • 2
    Your code is equivalent to `return true;` (since the `if(false)` part is always ignored. `return true` will show a prompt; the only value that won't show a prompt is `undefined` (so, either `return undefined;` or `return;`). This doesn't seem to have anything to do with the use of a conditional. – apsillers Feb 09 '15 at 17:06

1 Answers1

2

I've added a textbox to the example and the changed the condition to check if the value is 1 before prompting the message.

<html>
<head>
    <script type="text/javascript" src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
</head>

<body>
<!-- added textbox for verification //-->
<input type="text" id="text1"> </input>

<script type="text/javascript">
    $(document).ready(function ()
    {
        $(window).bind('beforeunload', function () {
            //changed the if condition to check if the value of the textbox is 1 and only prompt if it is 1
            if ($('#text1').val()=="1")
                return "Are you sure? Your changes will be lost!";
        });
    });
</script>

</body>
</html>