title: Creating a hidden field in codebehind and accessing it via clientside javascript
body: <p>I want to add a hidden field programmatically to an asp.net page, read and change it via javascript. So far my code fails at reading the added hidden field.</p>
  
  <p>Here is a simple example:
  Default.aspx:</p>
  
  <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
  &lt;html xmlns="http://www.w3.org/1999/xhtml" &gt;
  &lt;body&gt;
      &lt;input type="hidden" id="myHiddenField1" value="blub" runat="server" /&gt;
  
      &lt;button onclick="myFunction()"&gt;click me&lt;/button&gt;
      &lt;script&gt;
          function myFunction() {
  
              var testVar = document.getElementById("myHiddenField1").value; //works: field defined in aspx page
              var testVar2 = document.getElementById("myHiddenField2").value; //fails, Object required: field defined in codebehind
  
              alert(testVar);
          }
      &lt;/script&gt;
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>Default.aspx.cs (includes ommited):</p>
  
  <pre><code>public partial class _Default : System.Web.UI.Page
  {
      protected void Page_Load(object sender, EventArgs e)
      {
          //Page.RegisterHiddenField( "myHiddenField2", "bla!" ); doesnt work either
          Page.ClientScript.RegisterHiddenField( "myHiddenField2", "bla" );
      }
  }
  </code></pre>
  
  <p><strong>[edit]</strong></p>
  
  <p>The error i receive is: Microsoft JScript runtime error: Object required. If i add an alert(testVar2) and ignore the error the message box displays "undefined".</p>
  
  <p><strong>[/edit]</strong></p>
  
  <p><strong>[edit2]</strong></p>
  
  <p>[removed edit, since i was wrong]</p>
  
  <p><strong>[/edit2]</strong></p>
  
  <p>Summering up my question: How do i create a hidden field in codebehind so i can get and set it from javascript? </p>