简体   繁体   中英

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.

You get on client side the drop down list, and check the index, your code will probably be as:

<script>
window.onbeforeunload= function() 
    { 
        if(document.getElementById('<%=cbOrderSpareCustomer.ClientID%>').selectedIndex > 0)
        {
            return "Custom message here"; 
        }
        else
        {
            return true;
        }
    };
</script>

I think...

window.onbeforeunload = function(e) {
    if (document.getElementById('cbOrderSpareCustomer').selectedIndex > 0) {
        if (!confirm('Are you sure')) {
            return false;
        }
    }
}

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'); } }

If you're using JQuery

<script type="text/javascript">
    $(window).bind('beforeunload', function () {
        if ($("select[name='cbOrderSpareCustomer'] option:selected").index() > 0) {
            return 'Your data will be lost.';
        }
    });
</script>

You don't want else return true or it will still prompt (at least, IE prompts)

My solution:

<script type="text/javascript"
function setDirty() {
            window.onbeforeunload = function () {
                return 'The data will be lost if you leave this page!'
            }
        }
</script>

With the attribute onCange="setDirty()" added to the dropdownlist.

Thanks all for helping!

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