If you’re sure the entrance is int
can directly apply 0 or 1 to the .checked = status;
(even though .prop('checked', status)
) (as @Sergio explained):
var status = 1; //valor recebido
$("#status").prop('checked', status);
But for other cases where there is no automatic conversion you use so with !!
, as long as you’re sure to be a 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’re not sure you’re getting one you’re getting string
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);
There’s no need
!!
it is converted into boolean even with native Javascript.– Sergio
@Sergio Para
.prop()
or.checked = 1
you are correct, the question that I pointed this to any situation where there is no "automatic" conversion, to similar doubts (is that I focused on the title).– Guilherme Nascimento
It would not be better to force the int using
!!parseInt(status)
, because if it isstring
will result intrue
in both cases. : S– Inkeliz
@Inkeliz yes, in the case of 1 and 2, but as AP had placed a
var status = 1;
I assumed the entrance would always beint
and another I followed the title, but I will add a better explanation.– Guilherme Nascimento