A noob with a problem here.
Scenario 1:
do { var yourName = prompt("Who are you?"); } while (!yourName); console.log(yourName);
Returns a string if something was typed into the prompt box.
If you didn't type anything and click "OK", it continues to ask for name. And if you click "Cancel", it still continues to ask.
Scenario 2:
do { var yourName = prompt("Who are you?"); } while (yourName != true); console.log(yourName);
Keeps asking for a name even if you type something or click "OK" or "Cancel". It just gets stuck. Infinite loop?
In scenario 1 the program works like this:
Do this (ask for name) while yourName is false (false meaning undefined). If yourName gets a defined value console.log the name.
I know that an empty string ("") is converted in boolean value as false. And i also know that it is converted from false to true because of ! before being negated by ! from true back to false. So if the program is getting the empty string by clicking "OK" or "Cancel", it is getting the original false, converted to true and then the converted true is negated by ! back to false, and that's why it is keeping asking for a name for as long as you don't type it. And when you type in something, the typed value is true, it gets checked by !, we get back true and it is being console.logged.
In scenario 2 the program works almost like in 1st case but it doesn't accept any typed values because when you type in something, it is true in boolean, true != true will give us false so it will ask for name again. But here is what i don't understand about 2nd case: when you click "OK" or "Cancel", they are translated as false, and false != true is true, which should pass and console.log the empty string.
I think i understood something wrong or...i don't even know. Please explain me this guys.
Also this is quiet strange too:
do { var yourName = prompt("Who are you?"); } while (typeof(yourName) != true); console.log(yourName);
And
do { var yourName = prompt("Who are you?"); } while (typeof(yourName) != false); console.log(yourName);
Scenario 1:
Cancel returns null and OK returns empty "", and both satisfies !yourName.
Instead just check if user has clicked cancel or not by adding a condition yourName != null
Demo
do {
var yourName = prompt("Who are you?");
} while (!yourName && yourName != null);
console.log(yourName);
Scenario 2:
OK doesn't return boolean so yourName != true will never fail - hence the infinite loop in this scenario as well.
When you use !yourName, the empty string '' is falsy and a non-empty string is truthy, so the boolean condition is true.
When you use yourName != true, both operands are converted to a number and then compared: loose comparison with ==. This means that comparing the string '1' to true evaluates to true.
console.log("'' and true:", +'', +true);
console.log("'your name' and true:", +'your name', +true);
console.log("'true' and true:", +'true', +true);
console.log("'1' and true:", +'1', +true);
This is one of those places that JavaScript is just out to get you. It is quite commonly accepted to use !yourName, but being explicit with (yourName != null && yourName != '') will not hurt.
Related
I want to be able to have an if statment saying that if an element is equal to Infinity, it gives out a different phrase than "Infinity"(my element is an input box) here is my if statement:
if (document.getElementById("box").value === Infinity) {
document.getElementById("box").value = "STOP PRESSING BUTTONS"
}
I'm still very new to javascript/html so I might've gotten some of the terms wrong.
Try this...
if (result == Number.POSITIVE_INFINITY || result == Number.NEGATIVE_INFINITY)
{
// ANY LOGIC
}
You could possibly use the isFinite function instead, depending on how you want to treat NaN isFinite returns false if your number is POSITIVE_INFINITY, NEGATIVE_INFINITY or NaN.
if (isFinite(result))
{
// ANY LOGIC
}
I was writing a very simple function but can't get the if statement to work correctly.
$("#supplyRequestTextbox-clients").live("blur", function() {
var textboxValue = $(this).val().replace(/\d+/g, '').replace(" ", "");
if (textboxValue == "NO ACCOUNT") {
$(".controlBarTextboxNoAccount").fadeIn("fast");
}
});
The value in the input #supplyRequestTextbox-clients represents a client and is organized like this:
id# FirstName LastName email phone
An example: 000001 John Doe johndoe#johndoe.com 123-456-7890
When no account is found, the string appears exactly like this:
000906 NO ACCOUNT
In my function I strip the digits and first space, then check to see if it works in my if statement. I have alerted textboxValue and it is passing correctly, but no matter that textboxValue is, the if statement never fires.
Change the if condition to:
if(textboxValue.indexOf("NO ACCOUNT") !== -1)
indexOf("NO ACCOUNT") finds "NO ACCOUNT" within textboxValue, if it can't find it -1 is returned. So this will be true if "NO ACCOUNT" is anywhere in your string.
Use == for comparisons. You are assigning a truthy value, so the statement always fires.
Change your if condition to
if (textboxValue == "NO ACCOUNT")
If you do
if (textboxValue = "NO ACCOUNT")
You're actually assigning "NO ACCOUNT" to textboxValue and evaluating the result as bool.
Try doing this:
$("#supplyRequestTextbox-clients").live("blur", function() {
var textboxValue = $(this).val().replace(/\d+/g, '').replace(" ", "");
// check what textboxValue evaluates to:
alert(textboxValue);
if (textboxValue == "NO ACCOUNT") {
$(".controlBarTextboxNoAccount").fadeIn("fast");
}
});
Use == for comparisons as Kolink suggest.
You are replacing " " with "", IE. removing all spaces so your if statement will never return true.
The following is common code floating around online that checks if cookies are enabled in a particular browser:
var cookieEnabled = (window.navigator.cookieEnabled) ? true : false;
if (typeof navigator.cookieEnabled == "undefined" && !cookieEnabled) {
document.cookie = "testcookie"
cookieEnabled = (document.cookie.indexOf("testcookie") != -1) ? true : false
}
if (!cookieEnabled) {
// do some work
}
Why are the first and fifth lines ternary statements? Does
var cookieEnabled = (window.navigator.cookieEnabled) ? true : false;
catch some case that the following wouldn't?
var cookieEnabled = (window.navigator.cookieEnabled);
The same goes for the fifth line.
The ternary statement at the first line is useful in that it coverts a possible non-boolean value into a boolean one. Consider the following code
window.navigator.cookieEnabled = "evil people do this";
The above is legal and as the value says evil people do do this. Without the ternary statement the following code wouldn't execute as expected
if (cookiesEnabled === false) {
// ...
}
To be precise:
(window.navigator.cookieEnabled) ? true : false
is equivalent to:
!!window.navigator.cookieEnabled
However:
(document.cookie.indexOf("testcookie") != -1) ? true : false
can be simply replaced by:
document.cookie.indexOf("testcookie") != -1
Finally:
cookieEnabled == false
can be changed to:
!cookieEnabled
So what's the problem with the first case? In JavaScript non-zero numbers, non-empty strings, etc. evaluate to true. So if(window.navigator.cookieEnabled) passes for cookieEnabled being equal to "foo" and 42 as well. If you really want to have a variebale of boolean type, you must negate it twice.
I got the Json "false" from server. I respond as bool but it's Json so it's in browser type is String instead of bool.
So if I run (!data) whenever I want to check "false" == false then they not worked.
So how can I parse bool from String in JavaScript then?
"true" == true and "false" == false. Then the code (!data) can check what it is [true and false]
If one of the operands is a boolean, convert the boolean operand to 1 if it is true and +0 if it is false.
When comparing a number to a string, try to convert the string to a numeric value.
from MDN Equality Operators page
Examples:
true == "true"; // 1 == NaN → false
true == "1"; // 1 == 1 → true
false == "false"; // 0 == NaN → false
false == ""; // 0 == 0 → true
false == "0"; // 0 == 0 → true
I would just explicitly check for the string "true".
let data = value === "true";
Otherwise you could use JSON.parse() to convert it to a native JavaScript value, but it's a lot of overhead if you know it's only the strings "true" or "false" you will receive.
var data = true;
data === "true" //false
String(data) === "true" //true
This works fine.
Try expression data == "true"
Tests:
data = "false" -- value will be false
date = "true" -- value will be true
Also, fix your JSON. JSON can handle booleans just fine.
If its just a json "false"/"true", you can use,
if(! eval(data)){
// Case when false
}
It would be more cleaner, if you restrict the code to accept only JSON data from server, and always jsonParse or eval it to JS object (something like jquery getJSON does. It accepts only JSON responses and parse it to object before passing to callback function).
That way you'll not only get boolean as boolean-from-server, but it will retain all other datatypes as well, and you can then go for routine expressions statements rather than special ones.
Happy Coding.
I think you need to look at how the JSON data is being generated. You can definitely have a normal JS boolean false in JSON.
{ "value1" : false, "value2" : true }
String.prototype.revalue= function(){
if(/^(true|false|null|undefined|NaN)$/i.test(this)) return eval(this);
if(parseFloat(this)+''== this) return parseFloat(this);
return this;
}
From: http://www.webdeveloper.com/forum/showthread.php?t=147389
Actually, you just need the first "if" statement from the function -- tests to find true or false in the code and the evals it, turning it into the boolean value
if(data+''=='true'){
alert('true');
}
Convert boolean to string by appending with blank string. and then compare with Stringobject.
I have a boolean value set as a hidden variable in the form and I have the below javascript .
$().ready(function() {
var flag = $('#popUpFlag').val();
alert("flag = "+flag);
if(flag){
alert("flag is true");
}else{
alert("flag is false");
}
})
These are the outputs for the alert .
flag =
flag is false
flag = false
flag is false
flag = true
flag is false
My concern is obviously the third output . When the flag is true , why is it printing "flag is false" , instead of "flag is true" . I tested it in IE8 and FF 4
Suggestions are welcome.
No, you don't have a boolean value in the hidden field. The value in the field is always a string.
When you use the string value as if it was a boolean value, you get unexpected results. A condition is false if the value is false, 0, "" or null, but the string "false" is neither, so it's evaluated as true.
If you want a boolean value, you have to parse the string. An easy way is to simply check if the string has a specific value:
var flag = $('#popUpFlag').val() === 'true';
flag is a string, so have this instead:
if (flag === "true") {
//true
}
else if (flag === "false") {
//false
}
Hmm... I suspect that the value you are using is a string, so you're seeing the value correctly in the alert, but not when it tries to look at it like a boolean.
How can I convert a string to boolean in JavaScript?
Just try ocnverting to boolean and see if it still gives you the same issue