2

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

2
  • Do you have a clientscriptmanager on the page? Commented Mar 18, 2013 at 10:47
  • 1
    If all you are doing is setting display none, why would you not do that from the codebehind? That would also guarantee a clean page load... Commented Mar 18, 2013 at 12:23

2 Answers 2

2

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>
Sign up to request clarification or add additional context in comments.

2 Comments

Still not working. Control is not going to method body. Is the calling method line correct?
Add script tag just before closing tag of body.
1

I assume that you have a label on your page like this;

<asp:Label ID="lblExample" runat="server" ClientIDMode="Static" Text="Hello"></asp:Label>

then I suggest you to use jQuery, and your js function should be like this;

<script type ="text/javascript" language="javascript">
   function hideLabel() 
   {
     $("#lblExample").hide();
   }
</script>

and finally call your js function like this in your code behind;

 ClientScript.RegisterStartupScript(this.GetType(), DateTime.Now.ToString(), "hideLabel();", true);

If you use ScriptManager andMasterPage then call like this;

 ScriptManager.RegisterStartupScript(this,this.GetType(), DateTime.Now.ToString(), "hideLabel();", true);

4 Comments

I am not able to make it invisible. ClientScript.RegisterStartupScript(GetType() is not coming in blue. Is it a problem?
Control is not going to that method in javascript.
Sanju did you used jQuery?
And c# has to accept GetType() or this.GetType(). they are same.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.