1

I have a div with a custom checkbox image. It is in a form. When clicked I alter the image to a "clicked image". I also adjust the value of a checkbox input which will get submitted to the form. The problem is even though the value of the "real" checkbox appears checked, it is always submitted as not checked.

    if (fakeCheck.hasClass('btn-palette-checkbox')) {
        fakeCheck.removeClass('btn-palette-checkbox');
        fakeCheck.addClass('btn-palette-checkbox-unchecked');
        $("#realCheck").attr("checked", false);
    }
    else {
        fakeCheck.addClass('btn-palette-checkbox');
        fakeCheck.removeClass('btn-palette-checkbox-unchecked');
        $("#realCheck").attr("checked", true);
    }

Edit: FYI the real checkbox is hidden

James
  • 2,951
  • 8
  • 41
  • 55

3 Answers3

3

Try it like this to mark it as checked:

$("#realCheck").attr("checked", "checked");

And like this to uncheck it:

$("#realCheck").removeAttr("checked");
Bogdan
  • 43,166
  • 12
  • 128
  • 129
3

From jQuery docs prop. This is if you are using jQuery 1.6+

The .prop() method should be used to set disabled and checked instead of the .attr() method. The .val() method should be used for getting and setting value.

$("#realCheck").prop("checked", true);
$("#realCheck").prop("checked", false);

Read more about using .prop vs using .attr here .prop() vs .attr()

Community
  • 1
  • 1
wirey00
  • 33,517
  • 7
  • 54
  • 65
1

Checked, like disabled, is a binary property, not an attribute. You need to use:

$("#realCheck").attr("checked", "checked");
Diodeus - James MacFarlane
  • 112,730
  • 33
  • 157
  • 176