-4

I've made a function to give a warning when a user navigates away when a certain form field is populated:

window.addEventListener("beforeunload", function (event) {
    var unsaved = "Are you sure you want to exit?";
    var text = $('.article_div textarea').val();
    if (text.length > 0){
        event.returnValue = unsaved;
        return unsaved;
    }
});

This actually works perfectly. However, I looked up returnValue and it is recommended to not use it. I have tried alternatives including removing event.returnValue = unsaved; and just using return unsaved. However, that also doesn't work - it still navigates away from the page.

Any ideas as to what I can do to make it work?

Alex Lussier
  • 113
  • 1
  • 9
Zorgan
  • 8,227
  • 23
  • 106
  • 207
  • 2
    "Any idea what I can do?" You cite one source; have you done more research? – Dexygen Aug 06 '18 at 22:50
  • 2
    You can't prevent that user leaves the page https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload – Emeeus Aug 06 '18 at 22:50

1 Answers1

1

If you use jQuery, event.returnValue can be omitted. See here.

$(window).on('beforeunload', function(event) {
 var unsaved = "Are you sure you want to exit?";
    var text = 'Test Text @@@';
    //var text = $('.article_div textarea').val();
    if (text.length > 0){
            return unsaved;
    }
});

See example here.

Slinky Sloth
  • 301
  • 2
  • 5
  • Thankyou - changing `window.addEventListener("beforeunload", function (event) {` to `$(window).on('beforeunload', function(event) {` works. – Zorgan Aug 07 '18 at 02:37