check / uncheck checkbox using jquery?

Irfan Ahmed picture Irfan Ahmed · Jul 2, 2013 · Viewed 986k times · Source

I have some input text fields in my page and am displaying their values using JavaScript.

I am using .set("value","") function to edit the value, add an extra checkbox field, and to pass a value.

Here I want to check that if value == 1, then this checkbox should be checked. Otherwise, it should remain unchecked.

I did this by using two divs, but I am not feeling comfortable with that, is there any other solution?

if(value == 1) {
    $('#uncheck').hide();
    $('#check').show();
} else{
    $('#uncheck').show();
    $('#check').hide();
}

Answer

Eric picture Eric · Jul 2, 2013

For jQuery 1.6+ :

.attr() is deprecated for properties; use the new .prop() function instead as:

$('#myCheckbox').prop('checked', true); // Checks it
$('#myCheckbox').prop('checked', false); // Unchecks it

For jQuery < 1.6:

To check/uncheck a checkbox, use the attribute checked and alter that. With jQuery you can do:

$('#myCheckbox').attr('checked', true); // Checks it
$('#myCheckbox').attr('checked', false); // Unchecks it

Cause you know, in HTML, it would look something like:

<input type="checkbox" id="myCheckbox" checked="checked" /> <!-- Checked -->
<input type="checkbox" id="myCheckbox" /> <!-- Unchecked -->

However, you cannot trust the .attr() method to get the value of the checkbox (if you need to). You will have to rely in the .prop() method.