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

3 Answers 3

3

Try it like this to mark it as checked:

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

And like this to uncheck it:

$("#realCheck").removeAttr("checked");
Sign up to request clarification or add additional context in comments.

Comments

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()

Comments

1

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.