Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"true" evaluation running even when value is false

I have a very simple piece of jquery that needs to check a boolean value returned from an ajax call and set a checkbox to checked if it's true.

console.log("loc: " + r.location.defaultLocation);
if( r.location.defaultLocation == true ) {
    $('#loc-default').attr('checked',true);
}

This runs in an onclick function that opens a modal form - if the location info that is returned indicates that this is the default location, the checkbox should be checked. We have 5 of these on a single page - i.e. 5 locations the users can click on.

What I'm running into is that even if r.location.defaultLocation returns false (per the console.log line), the checkbox is still being checked. What am I doing wrong?

For those of you who insist that true/false must be a string, rather than a boolean:

This is the result of console.info(typeof(r.location.defaultLocation));

enter image description here

And this is the result of console.dir(r), if it helps. (group is blurred because it's sensitive info.)

enter image description here

FOUND THE ISSUE

Apparently jquery is remembering that #loc-default is checked after the first one was marked checked. I added an else to the function and now it works:

if( r.location.defaultLocation == true ) {
    $('#loc-default').attr('checked',true);
}
else {
    $('#loc-default').attr('checked', false);
}
like image 953
EmmyS Avatar asked Mar 08 '26 07:03

EmmyS


1 Answers

The only way I can see that happening is if defaultLocation is not actually the boolean false, but instead the string "false", which evaluates as true.

like image 96
DNS Avatar answered Mar 09 '26 20:03

DNS