How do you set the “Visible” property of a ASP.NET control from a Javascript function?

后端 未结 9 552
不知归路
不知归路 2021-01-17 09:49

Bascially I want to know the best way to hide/show an ASP.NET control from a Javascript function. I figured I would just access the control in Javascript using:

<         


        
相关标签:
9条回答
  • 2021-01-17 09:55

    You want to set the display style property to 'none' (to hide) or null to show.

       var theControl = document.getElementById("txtEditBox");
    
       theControl.style.display = 'none';
    
       theControl.style.display = null;
    

    Doing it the jQuery way:

       $('#txtEditBox').hide();
    
       $('#txtEditBox').show();
    
    0 讨论(0)
  • 2021-01-17 09:56

    Or if you don't want to use css:

    <asp:TextBox ID="txtBox" runat="server" style="display:none;">
    
    0 讨论(0)
  • 2021-01-17 09:57

    This should hide the control:

    theControl.style.display = 'none';
    
    0 讨论(0)
  • 2021-01-17 09:59

    The "Visible" property of an ASP.NET control determines whether or not it will be rendered on the client (i.e. sent to the client). If it is false when the page is rendered, it will never arrive at the client.

    So, you cannot, technically, set that property of the control.

    That said, if the control is rendered on the client because the Visible property is true when the page is rendered, you can then hide it using javascript like this:

    var theControl = document.getElementById("txtEditBox");
    theControl.style.display = "none";
    
    // to show it again:
    theControl.style.display = "";
    

    That assumes that the control's id attribute really is "txtEditBox" on the client and that it is already visible.

    Also, is that the best way to hide/show a ASP.NET control from a Javascript function?

    There is not necessarily a "best" way, although one better approach is to use CSS class definitions:

    .invisible { display: none; }
    

    When you want to hide something, dynamically apply that class to the element; when you want to show it again, remove it. Note, I believe this will only work for elements whose display value starts off as block.

    0 讨论(0)
  • 2021-01-17 10:03

    Set the style to "display: none".

    var theControl = document.getElementById("<%= txtEditBox.ClientID %>");
    theControl.style.display = "none";
    
    0 讨论(0)
  • 2021-01-17 10:08

    You can use the display property for this. But as Jason noted, this is a DHTML DOM (client-side) property that is completely independent from the ASP.NET (server-side) Visible property which controls rendering.

    theControl.style.display = "none";
    

    Display Property

    0 讨论(0)
提交回复
热议问题