JQuery - Checkbox not checking (visually)

ded*_*oki 2 html checkbox jquery

I'm trying to dynamically change the checked value. But visually checkbox constantly unchecked. Although the checked="checked" is present.

HTML:

<input type="checkbox" id="chk" /><br>
<button id="btn">Click me</button>
Run Code Online (Sandbox Code Playgroud)

JS:

$("#btn").click(function(){
  var chk = $("#chk").attr("checked");
  $("#chk").attr("checked", !chk);
});
Run Code Online (Sandbox Code Playgroud)

Link on JSFiddle: http://jsfiddle.net/USHRw/4/ - try click on the button several times.

How to fix this. Thanks!

j08*_*691 8

Use .prop() not .attr().

$("#btn").click(function () {
    var chk = $("#chk").prop("checked");
    $("#chk").prop("checked", !chk);
    if (!chk === true) {
        $("#lbl").text("Checked");
    } else {
        $("#lbl").text("Unchecked");
    }
});
Run Code Online (Sandbox Code Playgroud)

jsFiddle example

As the docs for .attr() say:

要检索和更改DOM属性(如表单元素的已检查,已选择或已禁用状态),请使用.prop()方法.