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 problem is that the above statement is always returning the client id of the div in the last control on the page.
I have checked the HTML and each div is given its own unique ID.
The full HTML of the control is…
<script type="text/javascript">
function ToggleHelpText() {
try {
var e = document.getElementById("<%= divHelpText.ClientID %>");
if (e.style.display == 'block')
e.style.display = 'none';
else
e.style.display = 'block';
}
catch (err) {
alert(err);
}
}
</script>
<asp:LinkButton ID="Help" OnClientClick="ToggleHelpText(); return false;" CausesValidation="false"
OnClick="btnHelp_Click" runat="server">Help</asp:LinkButton>
<div id="divHelpText" runat="server" visible="true" style="display: none">
</div>
What could be causing this and what is the work around?
Thank you
Your problem is that you’re defining the function
ToggleHelpTextmultiple 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
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 thisor try setting it in code: