Search code examples
javascriptasp.nettelerikonbeforeunloadconfirm

Exit confirmation in Javascript with Telerik controls


I'm using Telerik controls for my project. On my page, there are some links to another page, several radtextboxes and a radbutton (it causes a postback). When the textbox values are changed, the button becomes enabled. Then, in my window.onbeforeunload, I check if the button is enabled or disabled. If it is enabled, then the confirm dialog appears. The code looks like this :

window.onbeforeunload = function (evt) {
    var ClientGeneral_btnSave = $find('<%=btnSave.ClientID %>');
    if (ClientGeneral_btnSave.get_enabled() == true) {
    var message = 'You will lose unsaved data?';
    if (typeof evt == 'undefined') {
       evt = window.event;
    }
    if (evt) {
       evt.returnValue = message;
    }
    return message;
}

This code works well. When I close the tab, the confirm dialog appears. When I click on the links, it does. But, when I click on the btnSave itself, the dialog appears too, which is unsual. I want the btnSave NOT to cause onbeforeunload event

Please tell me how to do this.

Thank you in advance


Solution

  • It will fire onbeforeunload this if the btnSave posts back which it looks as if it is. Therefore you have a couple of choices

    1. Prevent the btnSave from posting back if you don't need it to. Easiest way to do it is put this attribute in the asp:Button markup

      OnClientClick="return false"

    2. Wire up a javaScript/jQuery method to disable the onbeforeunload event. I did this before by stashing an value in a hidden field and using this to signal that the onbeforeunload event should fire.

    for instance

    $('#<%= btnSave.ClientID %>').bind('click', function(e){
    
       $('#myHiddenFieldId').val('1');
    
    });
    

    and change your on beforeunload handler to check that the hidden field is not equal to 1 (make 0 the default i.e.

    window.onbeforeunload = function (evt) { 
    
       if( $('#myHiddenFieldId').val() != '1')
       {
          //your logic here
       }
    
    }
    

    You could probably do something better by unbinding the onbeforeunload handler in the btnSave click event using JQuery rather than using a hidden field to override.

    Option 2 can get fiddly though - so best of luck