最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jquery checkbox checkedunchecked - Stack Overflow

programmeradmin3浏览0评论

I am trying to do some checkbox manipulation with jquery. I have a modal popup and checkbox in it and I am using jquery to manipulate the checked mode. There is a variable which has either True or False, so if its True then check otherwise uncheck. But, in my case even when the value is False, the checkbox still stays checked. This is the code I am using:

$(document).on("click", ".open-EditCC", function () {            
            var life = $(this).data('life');           
            $('#<%=chkLife.ClientID%>').attr('checked', life);
            $('#editCC').modal('show');
          });

life variable gets either True or False but all the time the checkbox is checked, I set a breakpoint I can see that the value is False. Any idea what am I doing wrong? Thanks in advance, Laziale

I am trying to do some checkbox manipulation with jquery. I have a modal popup and checkbox in it and I am using jquery to manipulate the checked mode. There is a variable which has either True or False, so if its True then check otherwise uncheck. But, in my case even when the value is False, the checkbox still stays checked. This is the code I am using:

$(document).on("click", ".open-EditCC", function () {            
            var life = $(this).data('life');           
            $('#<%=chkLife.ClientID%>').attr('checked', life);
            $('#editCC').modal('show');
          });

life variable gets either True or False but all the time the checkbox is checked, I set a breakpoint I can see that the value is False. Any idea what am I doing wrong? Thanks in advance, Laziale

Share Improve this question asked Feb 7, 2013 at 20:54 LazialeLaziale 8,23548 gold badges155 silver badges271 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

The value of the checked attribute is "checked" or the checked attribute is not present so use this:

// This is assuming life has the string value of "True" or "False"
// if it's a boolean change to if (life)
if (life === 'True') {
    $('#<%=chkLife.ClientID%>').attr('checked', 'checked');
} else {
    $('#<%=chkLife.ClientID%>').removeAttr('checked');
}

I guess it should be enough to remove attribute when neccessary.

if(life){
 $('#<%=chkLife.ClientID%>').attr('checked', 'checked');
}
else

{
$('#<%=chkLife.ClientID%>').removeRttr('checked');
}
发布评论

评论列表(0)

  1. 暂无评论