How to convert numeric value to boolean?

1

I get a boolean value of the database, in which I want to set a checkbox dynamically. The value received is 0 or 1 . I tried to do it this way below:

var status = 1; //valor recebido
$("#status").prop('checked', status);  

However according to with the documentation of the method prop , you should receive as a parameter boolean or a function, and not a numeral.

How do I convert a numeric value to boolean ?

    
asked by anonymous 26.01.2017 / 23:42

3 answers

2

If you are sure that the input is int you can directly apply 0 or 1 to .checked = status; (even .prop('checked', status) ) (as @Sergio explained):

var status = 1; //valor recebido

$("#status").prop('checked', status);

But for other cases where auto-conversion does not exist, you can use !! as long as you are sure to be int :

var status = 1; //valor recebido

$("#status").prop('checked', !!status);

Or so using "ternary operator":

var status = 1; //valor recebido

$("#status").prop('checked', status ? true : false);

Now if you are not sure if you are getting a% s, you can check like this:

var status = '1'; //valor recebido

$("#status").prop('checked', status == '1');

If you just want to "convert" integers to Booleans:

var status = 1;

console.log('Com ==', status == '1'); //Este talvez seja o mais garantido
console.log('Com !!', !!status);
console.log('Com ternário', status ? true : false);
    
26.01.2017 / 23:43
2

tests the type of this variable first. If it is string it will always give true. Check with:

console.log(typeof status, status);

To be sure, use Number(status) , or status == '1' ? true : false .

$("#status").prop('checked', status == '1' ? true : false);  

Examples:

var status = '1';
$('#statusA').prop('checked', Number(status));
$('#statusB').prop('checked', status == '1' ? true : false);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputid="statusA" type="checkbox">
<input id="statusB" type="checkbox">
<input id="status_controle" type="checkbox">
    
26.01.2017 / 23:45
0

I would most likely do something like this:

var status = 1; // value received

$ ("# status") .pprop ('checked', Number (status)? true: false);

Using same ternary, and converting the value always into a Number, in case a value above 0 would be true, otherwise it would be false.

    
24.02.2017 / 14:32