jQuery: Check whether a checkbox is checked

If you have never done it before when you need to react on a checkbox being checked on unchecked, you might try using the jQuery attr function e.g.:

<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
        $(function() {
                $('#mycheckbox').click(function () {
                      if ($(this).attr('checked')) {
                                $("#mydiv").html("checked");
                        }
                        else {
                                $("#mydiv").html("unchecked");
                        }
                });
        });
</script>
</head>
<body>
<input type="checkbox" id="mycheckbox"/>
<div id="mydiv"></div>
</body>

Well, this will not work. The condition will always return false and you’ll never see that the checkbox is checked.

There are a few different ways to get this piece of information. Instead of “$(this).attr(‘checked’)”, you can use any of the following conditions.

First “checked” is not an attribute of our checkbox but a property. In some versions of jQuery, calling attr(‘checked’) will return true/false, in others it will return checked or not and in others it will return the checked attribute set when creating the checkbox. Here a table from the jQuery documentation:

$( elem ).attr( "checked" ) (1.6) "checked" (String) Initial state of the checkbox; does not change
$( elem ).attr( "checked" ) (1.6.1+) "checked" (String) Will change with checkbox state
$( elem ).attr( "checked" ) (pre-1.6) true (Boolean) Changed with checkbox state

Now, in jQuery 1.10, it doesn’t seem to ever return anything else than undefined.

So since it’s not actually an attribute but a property, the obvious solution is to use the prop function:

if ($(this).prop('checked')) {...} else {...}

Since checked is a property, you can also get the first object returned by $(this) and evaluate the checked property:

if ($(this).get(0).checked) {...} else {...}

While at it, you can switch back to a pure JavaScript solution:

if (document.getElementById('mycheckbox').checked) {...} else {...}

Another option is to use the :checked selector:

if ($(this).is(':checked')) {...} else {...}

Or if it looks to simple and you like it more complex:

if ($('#mycheckbox:checked').val() !== undefined) {...} else {...}

Well, I guess I’ve shown you enough different ways to do this. You just have to choose which one you like best. My personal favourite is using the prop function. But I guess the more pure JavaScript, the faster but I doubt your users will ever notice the difference (except if they have to work with millions of checkbox but in this case I’d sue your UI designer).

One thought on “jQuery: Check whether a checkbox is checked

Leave a Reply

Your email address will not be published.