Tags: app, asking, box, confirm, event, firing, forms, javascript, net, onbeforeunload, save, treeview, twice, user, web, window

Treeview firing javascript onbeforeunload event twice

On .Net » Web Forms

5,503 words with 2 Comments; publish: Tue, 01 Jan 2008 10:01:00 GMT; (10078.13, « »)

Hi,

I'm using the window.onbeforeunload event in my app to show a javascript confirm box asking the user if they would like to save their changes before navigating away.

window.onbeforeunload =function(){

if(checkChangesEnabled && changeMade)event.returnValue ="You will lose your unsaved changes.";

}

This event is fired once when the user clicks on links, postback buttons or closes the window - which is perfect.

However when clicking on a Treeview node the event is fired twice - so to proceed the user has to confirm that they don't want to save their changes twice.

Does anyone know why/how the treeview is doing this and a possible way around it?

Here is the Treeview code:

<asp:SiteMapDataSourceID="srcSitemap"ShowStartingNode="false"runat="server"/>

<asp:TreeView

ID="treeSiteMap"

runat="server"

DataSourceId="srcSitemap"

ShowLines="true"

ExpandDepth="0"

OnSelectedNodeChanged="treeSiteMap_Click"

PathSeparator="/"

EnableClientScript="true">

<Databindings>

<asp:TreeNodeBindingDataMember="siteMapNode"TextField="Title"ValueField="url"/>

</Databindings>

<SelectedNodeStyleBackColor="Blue"ForeColor="White"/>

</asp:TreeView>

All Comments

Leave a comment...

  • 2 Comments
    • I've fixed that with a setTimeout:

      var checkChangesEnabled =true;

      window.onbeforeunload = confirmExit;

      function confirmExit(){

      if(checkChangesEnabled && changeMade){

      event.returnValue ="You will lose your unsaved changes.";

      disableCheck();

      }

      }

      function disableCheck(){

      checkChangesEnabled =false;

      setTimeout("enableCheck()","100");

      }

      function enableCheck(){

      checkChangesEnabled =true;

      }

      The next problem to sort out is stopping the treeview firing onbeforeunload when the user expands a node... Again, any thoughts would be more than welcome!

      Cheers.

      #1; Tue, 01 Jan 2008 10:03:00 GMT
    • I just found this post after struggling with this problem on a LinkButton. It's simple and works great! Thank you so much! Very clever way to work around this problem.

      #2; Tue, 01 Jan 2008 10:04:00 GMT