0

I have a checkbox that I am checking and unchecking using jQuery, however I have come across a bug most major browsers:

if I change the checkbox to be checked, then unchecked and then checked again through using jquery, the little cross no longer shows even though if you inspect the element the checked attribute has been added correctly.

I have used the following code to change the checked attribute:

$('.checkbox').attr('checked', true);

substituting in false for unchecking the box.

Has anyone come across this problem before or know how to get around it?

Here is a fiddle that replicates the problem - click on the check, then uncheck and then check again, you will see the tick no longer appears

Pete
  • 57,112
  • 28
  • 117
  • 166

4 Answers4

5

DEMO

use .prop() instead of .attr()

$("#check").click(function (e) {
    e.preventDefault();
    $("#chk").prop("checked", true);
});

$("#uncheck").click(function (e) {
    e.preventDefault();
    $("#chk").prop("checked", false);
});

Read .prop() vs .attr()

Community
  • 1
  • 1
Tushar Gupta - curioustushar
  • 58,085
  • 24
  • 103
  • 107
0

You have to use prop for that : $("#chk").prop("checked", true);

http://jsfiddle.net/daL3R/2/

$("#check").click(function(e) {
    e.preventDefault();
    //$("#chk").attr("checked", true);
    $("#chk").prop("checked", true);
});

$("#uncheck").click(function(e) {
    e.preventDefault();
    //$("#chk").attr("checked", false);
    $("#chk").prop("checked", false);
});
Paritosh
  • 11,144
  • 5
  • 56
  • 74
0
$("#chk").prop("checked", false);
$("#chk").prop("checked", true);
carter
  • 5,074
  • 4
  • 31
  • 40
0

use this:

$("#check").click(function() {
   // e.preventDefault();
    $("#chk").prop("checked", true);
});

$("#uncheck").click(function() {
    //e.preventDefault();
    $("#chk").prop("checked", false);
});
Vijay Verma
  • 3,660
  • 2
  • 19
  • 27