Reputation: 12138
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));
And this is the result of console.dir(r)
, if it helps. (group
is blurred because it's sensitive info.)
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);
}
Upvotes: 3
Views: 258
Reputation: 28064
First of all i would check to see what r.location.defaultLocation
is
console.info(typeof(r.location.defaultLocation));
Then i would go from there but using above code:
if (!!r.location.defaultLocation && typeof(r.location.defaultLocation)==="string") {}
Upvotes: 0
Reputation: 532
Since your code appears to be correct, I would try handling the else statement and force the checkbox to not be checked.
if( r.location.defaultLocation == true ) {
$('#loc-default').attr('checked',true);
} else {
$('#loc-default').attr('checked',false);
}
Upvotes: 1
Reputation: 15104
I think r.location.defaultLocation
is the string "false"
. So if you use console.log
on it, you will see "false"
. But "false" == true
is true.
You can check the type of a variable with typeof
.
console.log(typeof r.location.defaultLocation); // Log the current type of r.location.defaultLocation
console.log(typeof false); // Display boolean
console.log(typeof "false"); // Display string
Upvotes: 2
Reputation: 38189
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.
Upvotes: 3
Reputation: 8540
Make sure r.location.defaultLocation
is a boolean.
Try if (!!r.location.defaultLocation) {}
to force the value to be of type boolean.
Upvotes: 2