Philo
Philo

Reputation: 1989

Javascript comparing boolean value to True

I am trying to compare a database (SQL) value (which is being returned correctly) to the boolean value 'true'. If the database bit value is = true then I want a div element to become visible, else stay hidden.

<script language="javascript">
    window.onload= function show_CTL() {
        if(<%=_CurrentUser.IsCTL%> == true){
            document.getElementById('CTL').style.visibility = "visible";
        } else{
            document.getElementById('CTL').style.visibility = "hidden";
        }
    }    
</script>

However I am getting the error, Javascript: 'True' is undefined.

I have tried many combinations of <%=_CurrentUser.IsCTL%> == 'true' or "true" or true or "True" or 'true' and even the === ... but all give me the same error message.

Any insights on how to resolve this issue will be greatly appreciated.

I have such comparisons successfully before with integer values such as:-

 window.onload= function show() {
    if(<%=_CurrentUser.RoleKey%> == 1 || <%=_CurrentUser.RoleKey%> == 2)
            document.getElementById('enr').style.visibility = "visible";
    else
            document.getElementById('enr').style.visibility = "hidden";
 }

Upvotes: 4

Views: 1609

Answers (4)

Amit Joki
Amit Joki

Reputation: 59292

Do this:

if("<%=_CurrentUser.IsCTL%>" === "True")

<%=_CurrentUser.IsCTL%> is returning True. So wrap it with string and compare them instead. Notice the '===' instead of '=='.

Upvotes: 5

Chuck
Chuck

Reputation: 237110

You need to convert your native boolean value to the string "true" before output. So, assuming ASP.NET MVC, I believe it looks like:

<%=_CurrentUser.IsCTL ? "true" : "false"%>

Upvotes: 0

Travis J
Travis J

Reputation: 82337

This has gotten me before as well. ASP.NET will return True for a boolean which is true. You have to make it a string and then compare it to the string version == "True" in order to get a proper conditional statement.

Conversely, you could also just make a variable in javascript

var True = true;

Upvotes: 2

Nivas
Nivas

Reputation: 18364

In

if(<%=_CurrentUser.IsCTL%> == true)

I think <%=_CurrentUser.IsCTL%> is getting evaluated to True before the code is seen by the browser.
The browser will see this as

if(True == true)

True does not make a lot of sense to the browser, thats why the error. For this true to be treated as a boolean, try one of this:

if(new Boolean('<%=_CurrentUser.IsCTL%>') == true)

or

if(new Boolean('<%=_CurrentUser.IsCTL%>'))

Upvotes: 2

Related Questions