Using jQuery to check/uncheck checkbox

Sat, Nov 2, 2013

Javascript Programming #javascript #jquery #programming

This happened few days ago when I wanted to write a script to check/uncheck checkbox using jQuery in one of the project I am working on. It sounds simple since I am using jQuery. So I started working on it and wrote the following script. (I simplified the code, of course.)

HTML

<input id="checkbox1" type="checkbox" />
<label for="checkbox1">Checkbox</label>
<p> 
    <a href="#" id="toggle">Toggle checkbox</a>
</p>
<p>
    checkbox is now <span id="status"></span>
</p>

Javascript

$('#toggle').click(function (event) {
    event.preventDefault();
    var checkbox = $('#checkbox1'),
        isChecked = checkbox.is(':checked'),
        status = $('#status');
    if(isChecked) {
        checkbox.removeAttr('checked');
        status.html('unchecked');
    } else {
        checkbox.attr('checked', 'checked'); 
        status.html('checked');
    }
});

As you can see from the javascript, whenever user click on the “toggle” link then the script will toggle the checkbox. I’ve put this script on jsFiddle for you to test. You can click on the toggle link to check/uncheck the checkbox.

Now you notice some strange behavior when you clicked on the toggle link few times. First two time it works perfectly fine. Then third time the checkbox was not toggled, but the status is shown as “checked”. Then after a few more clicks, the script no longer working. This is so weird. Why isn’t it work as expected?

I know I can’t be the only one, so I did some research on the Internet and found a few posts regarding this issue on StackOverflow. Turn out I should be using .prop() instead of .attr() to toggle the checkbox. And actually .prop() is the preferred way to access attributes in the element.

Here is the updated script.

Javascript

$('#toggle').click(function (event) {
    event.preventDefault();
    var checkbox = $('#checkbox1'),
        isChecked = checkbox.is(':checked'),
        status = $('#status');
    if(isChecked) {
        checkbox.prop('checked',false);
        status.html('unchecked');
    } else {
        checkbox.prop('checked', true); 
        status.html('checked');
    }
});

Of course, it on jsFiddle too. Here you go.