Search code examples
c#javascriptasp.netcode-behind

Call Javascript method from code behind


I have a function in Javascript which makes a label invisible. I want to call this function from the code behind. I am not able to make it invisible. Here are both the lines of code.

C# code behind:

          Page.ClientScript.RegisterStartupScript(GetType(), "MyFunction", "MyFunction();", true);

javascript:

         <script type ="text/javascript" language="javascript">
          function MyFunction()
          {
                 document.getElementById("Label8").style.display = 'none';

          }
          </script>

Pls let me know if there is any mistake. Looks like control is not going to method definition only.

Thank you


Solution

  • Use ClientID of server control (label) in getElementById or set ClientIDMode to static for label and make sure the availability of html elements to script, for that you can put script tag just before closing tag of body

    <script type ="text/javascript" language="javascript">
          function MyFunction()
          {
              document.getElementById("<%= Label8.ClientID %>").style.display = 'none';    
          }
    </script>