Search code examples
javascriptasp.netuser-controlshiddenfield

How to access asp hiddenfield value from UserControl in Javascript (getElementByID not working)


So I've gotten stuck trying to access a HiddenField value in my UserControl from my JavaScript.

In my user control I have:

<asp:HiddenField ID="HiddenField1" runat="server" />  

This user control is used in multiple places and sometimes multiple times on the same page so ClientIDMode = Static is not an option, and it must be runat = server as I need to access it in the code behind as well.

In my JavaScript I have tried the following:

document.getElementById('<%= HiddenField1.ClientID %>');
document.getElementById('HiddenField1');
$find("<%= HiddenField1.ClientID %>");

All of these return null. I have seen a number of "solutions" suggest

document.getElementById('ctl00_ContentPlaceHolder1_HiddenField1')

But that obviously poses problems for re-usability.

EDIT: The html generated by this is:

<input type="hidden" name="ctl00$ctl00$MainContent$MainContent$$ctl00$SomeUserControl$someOtherUserControl1$HiddenField1" id="MainContent_MainContent_SomeRepeater_SomeUserControl_0_someOtherUserControl1_0_HiddenField1_0" value="353">

The value is set in the code behind through other functions.

EDIT2: Generalised my code example


Solution

  • I couldn't find a way to make this work with hidden field and so I caved and just changed my object to an asp:Label with a CSSClass and stored the value in the text property.

    Not the best solution I know, but if anybody has a better suggestion please let me know.