"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 - ie 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);
}

由于你的代码看起来是正确的,我会尝试处理else语句并强制复选框不被检查。

if( r.location.defaultLocation == true ) {
    $('#loc-default').attr('checked',true);
} else {
    $('#loc-default').attr('checked',false);
}

我可以看到发生这种情况的唯一方法是,如果defaultLocation实际上不是布尔值false,而是字符串“false”,其值为true。


Make sure r.location.defaultLocation is a boolean.

Try if (!!r.location.defaultLocation) {} to force the value to be of type boolean.

链接地址: http://www.djcxy.com/p/74980.html

上一篇: 验证引擎有效时返回False

下一篇: 即使价值不真实,“真正的”评估仍在运行