简体   繁体   中英

jquery checkbox checked / unchecked

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

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');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM