Javascript comparing boolean value to True - 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";
}

Do this:
if("<%=_CurrentUser.IsCTL%>" === "True")
<%=_CurrentUser.IsCTL%> is returning True. So wrap it with string and compare them instead. Notice the '===' instead of '=='.

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%>'))

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;

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"%>

Related

issues with localStorage and saving values

I have a program where I have these strings being added to an array. However, there are many strings that are triggered by a certain condition, which can be met multiple times, however I only want it to be added on the first occurrence. So I have implemented a system where the event of adding the string to the array is triggered by the original condition, and a boolean expression. Here is an example of one of those conditions:
if (count >= 10 && displayMulti == true) {
consoleData.shift()
consoleData.push("Multi available")
displayMulti = false
window.localStorage.setItem("display_multi", String(displayMulti))
updateConsole()
}
When the string is added to the array, the boolean, displayMulti, is set to false so that it will not trigger again. However, upon refreshing the page, it will still trigger. I'm not sure why because I feel like I have saving the values to localstorage correctly. Code is below:
if (window.localStorage.getItem("display_multi") != null ) {
displayMulti = Boolean(window.localStorage.getItem("display_multi"))
} else {
console.log("here")
var displayMulti = true
}
There "here" console log statement is not triggered. So I have no idea why this would keep triggering because I don't see how the boolean is true. I've tested at like so many different points I genuinely have no idea what's wrong. I also don't think those values are affected anywhere else in my code. Any help is appreciated.
Here is a solution that properly parses your string as a boolean. Instead of Boolean(), a conditional (window.localStorage.getItem("display_multi") === 'true')(window.localStorage.getItem("display_multi") === 'true') is used.
if (window.localStorage.getItem("display_multi") != null ) {
displayMulti = (window.localStorage.getItem("display_multi") === 'true')
} else {
console.log("here")
var displayMulti = true
}
if (count >= 10 && displayMulti == true) {
consoleData.shift()
consoleData.push("Multi available")
displayMulti = false
window.localStorage.setItem("display_multi", String(displayMulti))
updateConsole()
}

test for null not working

I have a an onclick function, inside this function I want to create a condition for the way some elements are shown in the textarea. added this in the function:
bPlace = bookForm.txtPlace.value;
if (bPlace="null") {
bPlace="!."
}
bookForm.myText.value = bPlace
according to this condition when the value in txtPlace in myForm is not null it should show anything the user puts in. But when I test it, when I type something, instead of showing that, it still shows the (( !. )) in the textarea.
I should say I used "Undefined" instead of Null and still the same thing happened
Can you please tell me what am I doing wrong?
The problem is you are using assignment operator instead of comparision operator
The statement bPlace="null" will assign the string null to bPlace and will return it, which is a truthy value so the if block will always get executed.
bPlace = bookForm.txtPlace.value;
if (bPlace == "null") {
bPlace = "!."
}
bookForm.myText.value = bPlace
But since bPlace is a input value, I think what you are trying to do is if the input is left blank you want to put a default value in that case you can check
bPlace = bookForm.txtPlace.value;
if (!bPlace) {
bPlace = "!."
}
bookForm.myText.value = bPlace
Demo: Fiddle
Which can be further shorten to
bookForm.myText.value = bookForm.txtPlace.value || '!.';
Demo: Fiddle

javascript passing the result of a boolean comparison confusion

I've been working through some text book to learn web development and i've become confused on an example. The example creates a meter element and fills it with some attributes. There is then some javascript to check for browser support for the tag. The part where i'm confused is after the first expression returns either true or false for the support, shouldn't there be a check for if true or false was returned on the following if statement? also as an aside, when the create element builds the element does is give it default values, or grab values from an existing meter in the html.
The check for support is as follows.
var noMeterSupport = function(){
return(document.createElement('meter').max === undefined);
}
the next part that builds the meter if the support isn't found is below. This is where i become confused as it seems to take either value and continue without checking if it was true or false.
if (noMeterSupport()) {
var fakeMeter, fill, label, labelText, max, meter, value;
value = meter.attr("value");
meter = $("#pledge_goal");
max = meter.attr("max");
labelText = "$" + meter.val();
fakeMeter = $("<div></div>");
fakeMeter.addClass("meter");
label = $("<span>" + labelText + "</span>");
label.addClass("label");
fill = $("<div></div>");
fill.addClass("fill");
fill.css("width",(value / max * 100) + "%");
fill.append("<div style='clear:both;'><br></div>");
fakeMeter.append(fill);
fakeMeter.append(label);
meter.replaceWith(fakeMeter);
}
The body of the if is only executed if noMeterSupport() returns true. The condition in an if statement requires something "truthy", i.e. something that can be interpreted as true or false. Since the function returns a boolean value, that is sufficient. (See first Google hit for truthiness javascript, which is a good explanation.)
EDIT: Forgot about your second question. When a new element is created with document.createElement, it does indeed get default values. In your example, the default value of max for a <meter> is 1.
if (noMeterSupport()) { checks the return value. It means exactly the same as this:
var supported = noMeterSupport();
if(supported) {
I hope that I understand your question correctly and will try to answer it.
So you would expect something like this:
if (noMeterSupport() == true)
Actually, this is equivalent to this:
if (noMeterSupport())
And if you want to check false:
if (noMeterSupport() == false)
This is equivalent to:
if (!noMeterSupport())
This statement will make the function either return true or false:
return(document.createElement('meter').max === undefined)
basically it would be synonymous with writing:
if(document.createElement('meter').max === undefined) {
return true;
} else {
return false;
}
That makes the value of noMeterSupport() either true or false.
var noMeterSupport = function(){
return(document.createElement('meter').max === undefined);
}
noMeterSupport returns the result of the comparison document.createElement('meter').max === undefined.
The comparison will be either true or false, ok?
So, now, when you do
if (noMeterSupport()) { /*then do something*/}
is like saying
if (/*the result of noMeterSupport() is true*/) {/*then do something*/}
So, this if statement will only run if noMeterSupport returns true
var noMeterSupport = function(){
return(document.createElement('meter').max === undefined);
}
This section of code is not actually doing the check, it is defining a function called noMeterSupport.
The code is not actually run until the function is called. It is called by adding () to the function name.
noMeterSupport()
Your if() statement is where it is being called as it the brackets.
You expect a boolean condition inside the if statement:
if(<boolean_condition>)
{
...
}
The noMeterSupport() is actually returning true or false, so the
if(noMeterSupport())
is converted to if(true) or if(false)
depending on the result of the document.createElement('meter').max === undefined evaluation.
You are receiving a boolean condition and the if statement works fine.
As a beginner, there's two points to quickly learn in programming :
The comparison operators == and === not only do the comparison, but returns in fact the result of this comparison (you can place it in var to test)
var bool = 1 === 2;
console.log(bool); // will print false
The test if(boolean === true) is equivalent to if(boolean), and the test if(boolean === false) is equivalent to if(!boolean)

If-statement fail in javascript

For several hours now am I trying to make a simple game, but one if-statement is failing:
function checkDiagonaal() {
if (document.getElementById("11").src.indexOf("o.png") &&
document.getElementById("22").src.indexOf("x.png") &&
document.getElementById("33").src.indexOf("o.png"))
{
winnaar = true;
}
}
The condition is not true, yet the variable winnaar is set on true. I don't see what I am doing wrong. Very probably just a little mistake.
I also tried this code:
if(document.getElementById("11").src === "images/o.png")
but this returns false (even when the condition is true). I would like to know why?
Use ...indexOf(...) >= 0 in such conditions.
indexOf returns -1 when the value is not found, -1 is truthy
From the MDN(great resource!):
"The indexOf() method returns the index within the calling String
object of the first occurrence of the specified value [...] returns -1
if the value is not found."
When statements get big they become a bit unreadable, it might be fine now, but if you need to add more checks, I would suggest a different approach:
function checkDiagonaal() {
var ids = [11,22,33];
var strs = ['o.png','x.png','o.png'];
var winnar = ids.every(function(id,i) {
return document.getElementById(id).src.indexOf(strs[i]) > -1;
});
}

Evaluate Razor variable in javascript

I need to evaluate a razor variable inside a JavaScript function. Given the following code:
#{var unseenNotificationsExist = false;}
#foreach(var notification in viewModel)
{
if (notification.WasSeen == false)
{
unseenNotificationsExist = true;
break;
}
}
I need to evaluate the unseenNotificationsExist variable in JavaScript like this:
if(#unseenNotificationsExist == true)
$('#unseenNotifCount').addClass('notifNotSeen');
However, when I debug the JavaScript code, I get this:
if(True == true)
and also I get the following error:
Uncaught ReferenceError True is not defined
var unseenNotificationsExist = #(unseenNotificationsExist?"true":"false") ;
//the line above must be part of your view
if(unseenNotificationsExist === true)
$('#unseenNotifCount').addClass('notifNotSeen');
//this can be part of your js file or alternatively and less
//preferably part of your view
I found a workaround: I added this
var True = true
Now, in javascript there is a variable "True" defined and the evaluation comes down to True == true, which returns true.
I prefer to use Json.Encode , whenever i want to convert the model data to JSON objects or JSON variables .
For converting an object(dto) of model to javascript
var accountDto = #Html.Raw(Json.Encode(#Model.AccountDto))
For converting a (bool)property of model
var isTrue = #Json.Encode(Model.IsTrue)
If you want to not have the the JavaScript rendered, use Daniele's suggestion.
If you insist on making the comparison in JavaScript:
if(#unseenNotificationsExist.ToString().ToLower() === true)
You tried with:
if('#unseenNotificationsExist' === 'True')
$('#unseenNotifCount').addClass('notifNotSeen');
try using
if('#unseenNotificationsExist')

Categories

Resources