Skip to content Skip to sidebar Skip to footer

<%= X.clientid %> In Repeated User Control Returning Wrong Value

I have asp .net user control that has <%= myDiv.ClientID %> in a piece of javascript hosted in the html template. This control is placed on a page a number of times. The prob

Solution 1:

Your problem is that you're defining the function ToggleHelpText multiple times. Each definition has the ID of one control hardcoded into it, and you're only left with the last definition and the last ID as they overwrite each other.

As a simple step, change your code to

<scripttype="text/javascript">functionToggleHelpText(id) {
     try {
          var e = document.getElementById(id);
          if (e.style.display == 'block')
             e.style.display = 'none';
         else
             e.style.display = 'block';
     }
     catch (err) {
         alert(err);
     }
 }
</script><asp:LinkButtonID="Help"OnClientClick='ToggleHelpText(\'<%= divHelpText.ClientID %>\'); return false;'
  CausesValidation="false"
  OnClick="btnHelp_Click" runat="server">Help</asp:LinkButton><divid="divHelpText"runat="server"visible="true"style="display: none"></div>

This will continue to overwrite the function multiple times, but now the ID itself will not be overwritten as it's not hardcoded into the function.

In future you can figure out how not to define the function multiple times.

NB I'm a little unsure of the quoting in the OnClientClick. If it doesn't work, try this

OnClientClick='ToggleHelpText(<%="\""+ divHelpText.ClientID+"\""%>); returnfalse;'

or try setting it in code:

Help.OnClientClick =
    "ToggleHelpText('" +
    divHelpText.ClientID +
    "'); return false;";

Solution 2:

one work around can be

<scripttype="text/javascript">functionToggleHelpText(id) {
     try {
          var a = document.getElementById(id);
          var e = a.nextSibling();
         if (e.style.display == 'block')
             e.style.display = 'none';
         else
             e.style.display = 'block';
     }
     catch (err) {
         alert(err);
     }
 }
</script><asp:LinkButtonID="Help"OnClientClick='ToggleHelpText(this.id); return false;'CausesValidation="false"OnClick="btnHelp_Click"runat="server">Help</asp:LinkButton><divid="divHelpText"runat="server"visible="true"style="display: none"></div>

If you don't mind using Jquery you will get better substitute for nextsibling() as nextsibling() or nextElementSibling() has cross browser compatibility issue.

Post a Comment for "<%= X.clientid %> In Repeated User Control Returning Wrong Value"