how we can covert a string to boolean? [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How can I convert a string to boolean in JavaScript?
I have a select list with 2 options in it, yes or no, something like:
<select size="1">
<option value="true">yes</option>
<option value="false">no</option>
</select>
Now i want to use the selected value in the jquery-UI button disabled property , means :
$("button").button({ disabled : $("select").val() });
Now my problem is that the value which we will get by $("select").val() is string and for
disabled property we need boolean. So i want to know that is there any method just like
pareInt or parseFloat by which we can convert a string to boolean ?

var value = ('true' === $("select").val() );

You can use the third one:
var num = +something; //toNumber
var str = something + ""; //toString
var bol = !!something; //toBoolean
That will turn 0, "", false, null, undefined, NaN to false, and everything else to true
But using my deduction powers, you want something like "false" -> false, for this you can use one of these:
var bol = something === "true"; //false for anything different than true
var bol = something !== "false"; //true for anything different than false

var myBoolean = (myString === 'true') ? true : false;

Something like
$("select").val() == 'true'
should do the trick.

Depends how many times you want to do it. If its going to be littered throughout your code I would add in a function like:
Boolean.parse = function (str) {
switch (str.toLowerCase ()) {
case "true":
return true;
case "false":
return false;
default:
throw new Error ("Boolean.parse: Cannot convert string to boolean.");
}
};

Try with this code:
var myBool = myString == "true";

How about writing your own?
I'm not exactly firm in JavaScript Syntax but try this:
function a(inputString)
if(inputString == "true")
return true;
if(inputString == "false")
return false;
I'm sure there are better solutions. This one is just from the top of my head.

Related

JS Ternary functions with multiple conditions?

I have been using a ternary operator in JavaScript to modify the value of an object based on user input. I have the following code, which runs as it should:
var inputOneAns = inputOne == "Yes" ? "517" : "518";
As you can see, I am assigning a numeric string value to inputOneAnswhether a user has inputed "Yes" or "No". However, there may be a case that a user has not selected a value (as it is not required). If this input was left blank, I would like to assign an empty string "" to inputOneAns. Is there a wayf or me to embed an ternary operator inside of another ternary operator? To help clarify, here is the same function that I want to accompolish with my ternary function but with if else statements?
if (inputOne == "Yes"){
var inputOneAns = "517"
}else if (inputOne == "No"{
var inputOneAns = "518"
}else{
var inputOneAns = ""
}
Is it possible to include multiple expressions into a ternary function? Is there a better way to accomplish what I am looking for? Thanks for the tips in advance.
Yes you can go wild nesting ternaries. I find this version to be fairly readable:
var foo = (
bar === 'a' ? 1 : // if
bar === 'b' ? 2 : // else if
bar === 'c' ? 3 : // else if
null // else
);
but that's not a widely shared opinion, and you should probably stick to if/else or switch when working on a team.
Yes, you can use multiple condition in Ternary Operator. Hope this will help you.
var x=20;
var y = x<13 ? "Child" : x<20 ? "Teenage" : x<30 ? "Twenties" : "Old people";
console.log(y);
A switch statement is likely the best choice in a situation like this.
let inputOneAns;
switch(inputOne) {
case "Yes":
inputOneAns = "517";
break;
case "No":
inputOneNas = "518";
break;
default:
inputOneNas = "";
}
If you could do ternary operations beyond 2 conditions, they would become incredibly messy. You can put conditions together, but I've no idea why you would want that - that would be incredibly messy.
The most elegant and clean way is to take advantage of Object literals:
const Switch = (str) => ({
"Yes": "517",
"No": "518",
})[str] || '';
console.log(Switch("Yes")); // 517
console.log(Switch("No")); // 518
console.log(Switch("Non matching value")); // Empty
This has the advantage of being both readable and flexible.
Yeh you can chain them together much like using an else if statement, but it can sometimes be a bit hard to read though, so I tend to split mine over multiple lines.
var inputOneAns = inputOne == 'Yes' ? '517' :
inputOne == 'No' ? '518' : '';
However in this case I would suggest a switch statement seeing as you're comparing the same value for every case.
var r = inputOne == "" ? "" : (
inputOne == "Yes" ? "517" : "518");
Unfortunately JavaScript does not provide a super terse and readable way to do this. Personally I would just use some single-line if statements like this:
var inputOneAns;
if (inputOne === 'Yes') inputOneAns = '517';
if (inputOne === 'No') inputOneAns = '518';
else inputOneAns = '';
Which can be even cleaner if you abstract it into a function (note: no need for else in this case):
function getInputOneAns(inputOne) {
if (inputOne === 'Yes') return '517';
if (inputOne === 'No') return '518';
return '';
}
Personally, I don't really like switch statements for this for two reasons: firstly those extra break statements bloating the code, and secondly, switch statements are very limiting - you can only do simple equality checks, and only against a single variable. Besides, in the case that you know you will be always checking a single string I would favour a simple map object:
var map = { 'Yes': '517', 'No': '518' };
var inputOneAns = map[inputOne] || '';
Yes, and it does provide a cleaner code than switch statement.. with all the breaks..
inputOne == "Yes" ? "517" :
inputOne == "No" ? "518" : inputOneAns = "";
Seems like a classic use for a switch statement:
let inputOneAns = '';
switch(inputOne) {
case 'Yes':
inputOneAns = "517";
break;
case 'No':
inputOneAns = "518";
break;
default:
inputOneAns = "";
}
note you don't actually need the default case, but I find it makes things more readable.

javascript if statement checking for true/false

I wrote, what I thought, was a straight forward if statement in JS but it is running incorrectly.
function printLetter(LetterId) {
var studentflag = $("#IsStudent").val();
if (studentflag)
{
//do option 1
} else {
//do option 2
}
}
Everytime it runs, the studentflag var value is correct, but regardless of whether it is true or false, it goes into option 1. I am pretty sure I have done true/false checks like this before in JS, but do I need to spell it out (studentflag == true) instead?
This is known as truthy and falsy Values
The following values are always falsy:
false
0 (zero)
"" (empty string)
null
undefined
NaN (a special Number value meaning Not-a-Number!)
All other values are truthy:
including "0" (zero in quotes),
"false" (false in quotes) like if (studentflag) //being studentflag "false",
empty functions,
empty arrays, and
empty objects.
If #StudentFlag is either "true" or "false", then if(studentFlag) will always follow the true route because both are non-empty strings (truthy). You need to do something along these lines:
var studentflag = $("#IsStudent").val();
if (studentflag === "true") {
//do option 1
} else {
//do option 2
}
.val () doesn't return a boolean.
Try this instead;
function printLetter(LetterId) {
var studentflag = $("#IsStudent").is (':checked');
if (studentflag)
{
//do option 1
} else {
//do option 2
}
}
This is assuming #IsStudent is a checkbox. If it's not, try this (assuming the value is true (as a string, not a boolean));
function printLetter(LetterId) {
var studentflag = ($("#IsStudent").val () == 'true')
if (studentflag)
{
//do option 1
} else {
//do option 2
}
}
IMO there should be more context in the question. If submitted solution works for OP that is great, but for others using this as a resource, the accepted solution might not work in all cases.
The value retrieved from an element via JS actually depends on the input itself and its HTML structure. Here's a demo explaining the difference between using .val(), .attr('val'), and .is(':checked') with checkboxes and radios. All of those variants can pull different values from an element depending on its HTML structure and current UI state.
Fiddle : http://jsfiddle.net/h6csLaun/2/
var studentflag = $("#IsStudent").val();//This is a string .. not a boolean
if (studentflag === "true") //therefore this has to be string comparison
Or you can make studentflag boolean as follows:
var studentflag = $("#IsStudent").val() === "true";
if (studentflag) { ....

If condition on windows load not working in javascript

The following code is not working and cant understand why. What am I doing wrong?
$(function() {
var advanced = localStorage['advanced-search'];
alert(advanced);//this shows true
if((advanced == "true")|(advanced==true)){
//Code never reaches here
alert('click');
$('#advanced-search').trigger('click');
localStorage['advanced-search'] = false;
}
});
Check the OR operator. It should be like -
if((advanced == "true")||(advanced==true)){
This expression is not working:
if((advanced == "true")|(advanced==true)){
It’s enough to do:
if(advanced) {
because "true" as a string is also "truthy".
You are missing an extra |:
$(function() {
var advanced = localStorage.getItem['advanced-search'];
alert(advanced);//this shows true
if((advanced == "true") || (advanced==true)){
//Code never reaches here
alert('click');
$('#advanced-search').trigger('click');
localStorage['advanced-search'] = false;
}
});
OR operator needs to be two |..Like this:
if((advanced == "true") || (advanced==true)){
If the variable advanced is a BOOLEAN, then you can simply use this:
if(advanced) {
// code here..
}
I think there is mistake in your javascript code.so you can not use "|" instead of "||"
so try by the following code gets solved your error.
$(function() {
var advanced = localStorage.getItem['advanced-search'];
alert(advanced);//this shows true
if((advanced == "true")||(advanced==true)){
//Code never reaches here
alert('click');
$('#advanced-search').trigger('click');
localStorage['advanced-search'] = false;
}
});
As you say that a proper OR operator is still not working, then I suspect it must be a problem with the case.
Check this fiddle: http://jsfiddle.net/VTfQU/
Use this code to simplify your if condition:
var advanced = localStorage.getItem['advanced-search'];
advanced = advanced.toString().toLowerCase();
if (advanced == "true") {
$('#advanced-search').trigger('click');
localStorage['advanced-search'] = "false";
}
The idea is to convert your data into lowercase and then just check the condition on that value. I have added toString() just to be safe, anyway getting a value out of local storage will always be a string.

Variable not updating its value

var canAssignMultiple="true";
var canWithdrawMultiple="true";
function onCheckUncheck()
{
if($(':checkbox[name^="checkedRecords"]:checked').length>0)
{
$("input[name='checkedRecords']:checked").each(function()
{
debugger;
var canAssign = $(this).attr("canAssign").toLowerCase();
var canWithdraw = $(this).attr("canWithdraw").toLowerCase();
canAssignMultiple= canAssignMultiple && canAssign;
canWithdrawMultiple= canWithdrawMultiple && canWithdraw;
if (canAssignMultiple == "false")
$("#assaignbutton").attr("disabled", "disabled");
else
$("#assaignbutton").removeAttr("disabled");
if (canWithdrawMultiple == "false")
$("#withdrawbutton").attr("disabled", "disabled");
else
$("#withdrawbutton").removeAttr("disabled");
});
}
else
{
$("#assaignbutton").attr("disabled", "disabled");
$("#withdrawbutton").attr("disabled", "disabled");
}
}
The variable canAssignMultiple is becoming true when each() function is called the second time though its value has changed to false in the first iteration.It should retain its value evrytime the loop runs.How to do this?
boolean (false, true) values are different than strings ("false", "true")
try
var canAssignMultiple = true;
var canWithdrawMultiple = true;
function onCheckUncheck() {
if ($(':checkbox[name^="checkedRecords"]:checked').length > 0) {
$("input[name='checkedRecords']:checked").each(function() {
debugger;
var canAssign = $(this).attr("canAssign").toLowerCase() == "true"; // make this a boolean expression
var canWithdraw = $(this).attr("canWithdraw").toLowerCase() == "true"; // make this a boolean expression
canAssignMultiple = canAssignMultiple && canAssign;
canWithdrawMultiple = canWithdrawMultiple && canWithdraw;
if (canAssignMultiple === false) $("#assaignbutton").attr("disabled", "disabled"); // use false (instead of "false")
else $("#assaignbutton").removeAttr("disabled");
if (canWithdrawMultiple === false) $("#withdrawbutton").attr("disabled", "disabled"); // use false (instead of "false")
else $("#withdrawbutton").removeAttr("disabled");
});
}
else {
$("#assaignbutton").attr("disabled", "disabled");
$("#withdrawbutton").attr("disabled", "disabled");
}
}​
left comments where changes were made
As others have noted, the strings "true" and "false" do not function the same as the boolean values true and false. If you try to use a string in an if statement or with a logical operator such as &&, the string is converted to a boolean; and all non-empty strings are converted to true (i.e. they are "truthy"). That means the string "false" will work the opposite of how you expect, e.g. in ("false" && x) or in if ("false") {...}.
One way to fix your code is to change this line
canAssignMultiple = canAssignMultiple && canAssign;
to convert canAssign to a boolean in an explicit and correct way:
canAssignMultiple = canAssignMultiple && (canAssign == "true");
Then the && operator will work correctly, and canAssignMultiple will hold an actual boolean value.
And (as #mdmullinax noted, but I would do it differently) once canAssignMultiple is actually a boolean, you can change your if statements to treat them as such:
if (canAssignMultiple == "false")
should become
if (!canAssignMultiple)
And similarly with the corresponding withdraw stuff.
Does your HTML look like this?
<input canAssign="false" ...>
<input canAssign="true" ...>
If so, and you can't change the HTML, I suggest changing this:
canAssign = $(this).attr("canAssign").toLowerCase()
to this (to work with booleans from then on):
canAssign = $(this).attr("canAssign") == "true"
and this:
if(canAssignMultiple == "false")
to this (since it is a real boolean now):
if(canAssignMultiple)
If you can change HTML, I suggest you do it the HTML5-compliant way. First, all of your made up attributes should be prefixed data-. You can also change camelCase to hyphen-case. JQuery, when loading your data-attributes, will then perform the conversion from string if possible:
<input data-can-assign="false" ...>
<input data-can-assign="true" ...>
then jQuery will give you the boolean you want from this call:
canAssign = $(this).data("canAssign")
Of course, the same fix should be applied to all other string pseudo-booleans (that don't quite work with the boolean operators) as well.
The reason is: "false" is not exactly false. "false" && x will evaluate to x (not to "false" as you expect). On the other hand, false && x will evaluate to false.

Strange data-attribute boolean issue

I have a live -on click- event for a Header which has an arrow flipping up/down upon opening & closing it's contents.
The strangest thing is happening with ! followed by a variable -- which is supposed to flip it from true -> false, and vice versa. Basically it's not working at all, and it flips to false and stays there... Check out the fiddle to see what I mean.
I've deleted lots of code for the sake of brevity.
Demo Code
$(document).on('click', '.regimenHeader', function () {
var _state = $(this).attr('data-state');
if (_state === 'true') {
// do stuff
}
else {
// do stuff
}
// This is where the issue is happening, it isn't flipping the Boolean value
// !"true" = false, !true = false, it works with strings or booleans
$(this).attr('data-state', !_state);
});​
I can get it working perfectly fine if I do the following:
if (_state === 'true') {
// Manually flip the data-state boolean
$(this).attr('data-state', false);
}
Is there something I'm missing why this isn't working the way it should ?? Just wondering why it's doing this!
I think you are trying to do this:
http://jsfiddle.net/JKUJb/2/
if so, the problem was that you are using .attr() which returns a string, so if you convert:
!"true" //false
!"false" //false
.data() on the other hand returns the value already "casted
EDIT:
Just to be more clear, in javascript the only falsy values are:
false;
null;
undefined;
'';
0;
NaN;
So if you really wanted to use .attr(), you could, but I recommend that first you do:
var _state = $(this).attr('data-state') === 'true'; //if 'true' then true, false otherwise
Good luck!
Change your second line to:
var _state = $(this).attr('data-state') == 'true';
And in the if statement check for boolean:
if ( _state ) {
// do stuff
...
_state is a String (typeof _state === String //true) you need to convert it to a boolean first
(a String will alwase be true)
If you really want to use data- attributes for this, use jQuery's .data method to retrieve and set the value. It will automatically convert the string "true" into a Boolean, or the string "1" into a number:
$(document).on('click', '.regimenHeader', function () {
var _state = $(this).data('state');
if (_state) {
// do something
}
$(this).data('state', !_state);
});​
http://jsfiddle.net/mblase75/JKUJb/6/
Or you could toggle a class -- you can use the .hasClass method to return a Boolean:
$(document).on('click', '.regimenHeader', function () {
var _state = $(this).hasClass('data-state');
if (_state) {
// do something
}
$(this).toggleClass('data-state');
});​
http://jsfiddle.net/mblase75/JKUJb/3/

Categories