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
Related
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.
I have a value in a text input I need to verify as a date in the format dd/mm/yyyy. Below is my code. I always get true regardless of what I enter in the text input. Otherwise function works well. Always displays an alert with the value I put in the text input.
function checkDate(date)
{
var result;
var expression = /[0-9]{2}\/[0-9]{2}\/[0-9]{4}/;
result = expression.test(date.value);
if(result=true)
{
alert(date.value);
}
else
{
alert("false finally");
}
}
if(result==true)
{
alert(date.value);
}
instead having single "=" have "==" , else you can use like this
if (result)
{
alert(date.value);
}
and always remember this
"1" == 1 // true
"1" === 1 // false
An example of type coercion at work. Basically anytime your value is the "same" but the type isn't then == works.
Please use === everywhere. There's no need to use ==. checking for types is always better. If something breaks then you can convert from type a to type b
I am using the code below in JavaScript to change a string on the site to a Boolean value using JavaScript. when I alert test its says its true, but when I alter name bool is see flase any ideas why this would be the case.
var test = document.getElementById("name").value;
var nameBool= (String == test);
Compare the string to the value that you expect it to have when it should represent a true value:
var nameBool = test === "true";
I would guess that test is the boolean value of a checkbox? Then you would get a textual representation of it either by
var nameBool = String(test); // type conversion
or simpler
var nameBool = "" + test; // concatenation with empty string - implicit conversion
which then becomes "false" or "true", just as in your alert() (which did a stringification as well)
For the opposite, you'd use
var test = "true" // or "false"
var nameBool = test === "true" || (test === "false" ? false : throw new SyntaxError("non-boolean string value"));
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.