Philo
Philo

Reputation: 1989

Div element hide and show

I have a hidden div element.

<div class= "CTL" id="CTL" runat="server" style="display:none">
<p class ="divider">
CTL
    </p>
            <asp:Button ID="CTL_button" runat="server" Text="View CTL" 
            onclick="CTL_button_Click" />
</div>

I am trying to make the div element appear or stay hidden based on an SQL value returned on page Load:-

   window.onload= function show_CTL() {
    if("<%=_CurrentUser.IsCTL%>" == "True"){
       document.getElementById('CTL').style.display ="block";
     }
     else{
         // document.getElementById('CTL').style.display ="none";
         }

But the div element remains shown regardless of value returned...

It seems like only the true part of the loop gets executed...

Upvotes: 0

Views: 153

Answers (4)

Tim Vermaelen
Tim Vermaelen

Reputation: 7069

Cast the condition to a Boolean in JavaScript you can do it like this:

window.onload = function show_CTL() {
    var el = document.getElementById('CTL');

    if(Boolean("<%=_CurrentUser.IsCTL%>") && el){
        el.style.display = "block";
    }
    else{
        el.style.display = "none";
    }
}

If the Boolean object has no initial value, or if the passed value is one of the following:

0
-0
null
""
false
undefined
NaN

the object is set to false. For any other value it is set to true (even with the string "false")!

Now I wonder, why not simply add the condition inside the visible attribute?

<div class="CTL" id="CTL" runat="server" visible=<%=_CurrentUser.IsCTL%>></div>

No JavaScript needed this way.

Upvotes: 1

Eric
Eric

Reputation: 25014

visible and display are 2 different css property,
you set visible first, but later you change display,
you should change visible, not display, of cause you can use display instead of visible in the first place.

Upvotes: 1

bobthedeveloper
bobthedeveloper

Reputation: 3783

ASP.NET is changing the IDs, thats why you have to take the clientID of your element.

document.getElementById("<%= CTL.ClientID %>").style.display = "block";

Upvotes: 1

Taimour Tanveer
Taimour Tanveer

Reputation: 408

Use display:none to hide the div in first place

<div class= "CTL" id="CTL" style="display:none" runat="server">
<p class ="divider">
CTL
    </p>
            <asp:Button ID="CTL_button" runat="server" Text="View CTL" 
            onclick="CTL_button_Click" />
</div>

then you can show it with

   document.getElementById('CTL').style.display ="block";

Upvotes: 3

Related Questions