简体   繁体   中英

How to show message to user if they are trying to leave the page or close the window only if form data has been changed?

I have requirement in one of my projects where users would like to see a message before they leave the page or close the browser/window if the form data has been changed. I found this function that will catch the scenario if user is leaving the window or closing the browser.

window.addEventListener('beforeunload', function (e) {
    e.preventDefault();
    e.returnValue = '';
});

I'm wondering if there is a way to show that message only if form data has been changed. SO user in that case would know that data has changed. I did not find a lot about this topic or any constructive solutions so far. If anyone have any examples or suggestions please let me know.

Thank you.

If you're not using any modern framework you can build your custom Form State helper. When form is ready on DOM you can iterate over each input element and assign a data property say (data-init-val) and set its value equal to the input element value.

let inputs = document.querySelectorAll('form#userform input');
for(let inputEl of inputs){
    inputEl.setAttribute('oldVal', inputEl.value);
}

This way you're caching the existing form values. When user is closing the window you can run a function to compare current input values with the initial cached values via:

function checkFormState(){
  let inputs = document.querySelectorAll('form#userform input');
  let stateChanged = false;
  for(let inputEl of inputs){
    if(inputEl.getAttribute('oldVal') !== inputEl.value){
        stateChanged = true;
        break;
    }
  }

  return stateChanged;
}

Your eventListener can make an informed decision based on the stateChanged value. PS: You should modify the input element value caching/compare logic based on the input elements in your form.

Headover to https://jsfiddle.net/v9rztay6/ and see it in action.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM