Find all unchecked checkboxes in jQuery

I have a list of checkboxes:

<input type="checkbox" name="answer" id="id_1' value="1" />
<input type="checkbox" name="answer" id="id_2' value="2" />
...
<input type="checkbox" name="answer" id="id_n' value="n" />

I can collect all the values of checked checkboxes; my question is how can get all the values of unchecked checkboxes? I tried:

$("input:unchecked").val();

to get an unchecked checkbox's value, but I got:

Syntax error, unrecognized expression: unchecked.

Can anybody shed a light on this issue? Thank you!


Solution 1:

As the error message states, jQuery does not include a :unchecked selector.
Instead, you need to invert the :checked selector:

$("input:checkbox:not(:checked)")

Solution 2:

$("input:checkbox:not(:checked)") Will get you the unchecked boxes.

Solution 3:

Also it can be achieved with pure js in such a way:

var matches = document.querySelectorAll('input[type="checkbox"]:not(:checked)');

Solution 4:

You can do so by extending jQuerys functionality. This will shorten the amount of text you have to write for the selector.

$.extend($.expr[':'], {
        unchecked: function (obj) {
            return ((obj.type == 'checkbox' || obj.type == 'radio') && !$(obj).is(':checked'));
        }
    }
);

You can then use $("input:unchecked") to get all checkboxes and radio buttons that are checked.