saimiris_devel
saimiris_devel

Reputation: 667

beforeunload ignores condition

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>

Upvotes: 1

Views: 704

Answers (1)

Srinivas Jillella
Srinivas Jillella

Reputation: 21

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>

Upvotes: 2

Related Questions