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

834 Views Asked by At

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

2

There are 2 best solutions below

1
Matt On BEST ANSWER

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.

3
Angappan.S On

In code behind may be your code look like this

public void test()
{
   hdnvalue.Value = "Test";
    //After assign the value you should call client side function
   ClientScript.RegisterStartupScript(GetType(), "Script", "<script 
   language='javascript'>gethidden()</script>", false);
}

In javascript function should use like this

<script language="javascript" type="text/javascript">
 function gethidden() {
    var hdn = document.getElementById('<%=hdnvalue.ClientID%>');
    alert(hdn.value);
 }
</script>

I hope its help to you.