Javascript equality weirdness
I'm trying to fetch some data through ajax. One of the data determines whether or not a checkbox should be checked by default. If the ret开发者_高级运维urned variable isVisible
is 1
, then it should be checked, if its 0
then it should be unchecked. Here's the code:
$.getJSON(myUrl, function(result)
{
isVisible = result.isVisible;
// snip...
} );
Later on in the code:
var isChecked = (isVisible) ? true : false;
$("#visible").attr('checked', isChecked);
The problem is that, whether or not isVisible
is set to 1 or 0, the checked
variable is always being evaluated to true. I'm really not sure what the problem is. Perhaps isVisible
is being treated as a string ?? How do I resolve this?
Probably isVisible
is a string. "0"
is a truthy value in Javascript. Use this instead:
var checked = (isVisible==="1") ? true : false;
How about
isVisible = (result.isVisible == "1")
?
I guess "isVisible" is a string not a number, so it pass the test. Try parseint(isVisible, 10), an let me know
Ajax is asynchronous. you need to use callbacks.
$.getJSON(myUrl, function(result)
{
isVisible = result.isVisible;
// snip...
callback_setvis();
} );
function callback_setvis(){
var ischecked = (isVisible) ? true : false;
$("#visible").attr('checked', ischecked);
}
After reviewing your question again it seems the above might not work.
This might be an issue of attr
vs prop
if you are in jQuery 1.6 or greater you should do:
$("#visible").prop('checked', ischecked);
精彩评论