Search code examples
javascriptasp.netonbeforeunload

prompting a user when leaving page


On my page I have a combobox called cbOrderSpareCustomer. By default the selected index is set to 0.

when the user changes it, I consider the page containing data and when the user decides to leave the page I want to prompt him to let him know data will be lost.

I have seen many posts about this but I'm very new to javascript so I could use some help.

I understand I have to use:

<script>
window.onbeforeunload= function() { return "Custom message here"; };
</script>

But how do I make it work with the combobox?

like if cbOrderSpareCustomer.selectedIndex > 0 then prompt else just continue.

I also want to prevent it from showing the prompt on each postback.

I would like to see an example.


Solution

  • Follow the below steps to make this work

    1. Add onchange attribute to the combobox on serve side using the code: <select id="cbOrderSpareCustomer" onchange="setDirty()">
    2. Define your javascript as below

      var isDirty = true;
      function setDirty() { isDirty = true; } window.onbeforeunload = function () { if (isDirty) { return confirm('Your unsaved changes will be lost'); } }