How to detect unsaved changes on a form

Johannes Mweli
Giga Guru

Hi ServiceNow Community Developers,

Do you guys know if there is a way to detect if there are unsaved changes on a form before you dynamically navigate away from it? For instance I have a client script that opens up a UI page and some processing happens in that page. The problem I am running into is that when processing is done on the UI page and control returns back to the record I was at before invoking the UI page, the form reloads and all the fields that I had changed / populated before navigating away from the record get's lost. I have to redo them. What would be ideal is that before the client script invokes a UI page it first checks if there are unsaved changes and don't open a ui page if there are, that way nothing gets overridden when I return back from the UI page and reloads the form. 

Please advise.

Thanks,

Johannes

 

 

1 ACCEPTED SOLUTION

Allen Andreas
Administrator
Administrator

Hi,

You can place this at the top of your script for invoking the UI Page to give the option to stop it if the form hasn't been saved yet:

 if(g_form.modified){
    answer = confirm("Values on the form have changed.\nYou will lose any unsaved changes if you continue.");
    if (answer == false) {
      return false;
    }
  }

Please mark reply as Helpful/Correct, if applicable. Thanks!


Please consider marking my reply as Helpful and/or Accept Solution, if applicable. Thanks!

View solution in original post

3 REPLIES 3

Allen Andreas
Administrator
Administrator

Hi,

You can place this at the top of your script for invoking the UI Page to give the option to stop it if the form hasn't been saved yet:

 if(g_form.modified){
    answer = confirm("Values on the form have changed.\nYou will lose any unsaved changes if you continue.");
    if (answer == false) {
      return false;
    }
  }

Please mark reply as Helpful/Correct, if applicable. Thanks!


Please consider marking my reply as Helpful and/or Accept Solution, if applicable. Thanks!

Johannes Mweli
Giga Guru

That worked! Thank you very much Allen

You're welcome!

Please also mark as Helpful if it was.

Take care!


Please consider marking my reply as Helpful and/or Accept Solution, if applicable. Thanks!