Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript comparing boolean value to True

Tags:

javascript

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";
 }
like image 277
Philo Avatar asked Jan 10 '23 19:01

Philo


2 Answers

Do this:

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

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

like image 169
Amit Joki Avatar answered Jan 22 '23 12:01

Amit Joki


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%>'))
like image 32
Nivas Avatar answered Jan 22 '23 12:01

Nivas