picasa
picasa

Reputation: 33

Prompt only when closing browser not when clicking save button or when navigating away from page using javascript?

How to prompt when user typed something in the textbox and unknowingly close the browser?

Also if the user doesn't type anything in the input field and if close the browser, the browser should close without prompting. Browser should prompt only if the user changed something in the field. If I use onbeforeunload event, it promts for everything even when saving the page. Is there any way to solve my problem in javascript. Please help by giving me apt codes.

Upvotes: 2

Views: 2427

Answers (2)

Awad Maharoof
Awad Maharoof

Reputation: 2370

You can use window.onbeforeunload .
You can check if the user has entered any text, and if yes, you simply return the message that you want to prompted.

var hook = false; //

window.onbeforeunload = function() {
    var x = $('#box').val();
    if (x.length > 1) { //check is user has entered text
        hook = true;
    }

    if (hook) { //return message if there is text
        hook = false; //reset hook
        return "Did you save your work?"
    }
}​

Read more about window.onbeforeunload here
Here is a link to a demo

Upvotes: 2

Rups
Rups

Reputation: 639

Check this link: https://web.archive.org/web/20211020134123/https://www.4guysfromrolla.com/webtech/100604-1.shtml

It gives you information on how to handle onbeforeunload event.

The idea is to have a global flag on the page. When any change is done to the fields, this flag is set to true. When clicked on save button, then this flag needs to be set to false.

In the onbeforeunload event, check whether the flag is true, then show the message accordingly.

var needToConfirm = true;

window.onbeforeunload = confirmExit;
function confirmExit()
{
    if (needToConfirm)
    {
        // check on the elements whether any change has been done on the fields.
        // If any change has been done, then set message here.
    }
}

function saveClicked()
{
    needToConfirm = false;
}

Another way of doing the things, would be to set the needToConfirm flag when any change is made to the fields via onchange events.

Upvotes: 2

Related Questions