find all unchecked checkbox in jquery

2019-01-16 03:53发布

问题:

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!

回答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)")


回答2:

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



回答3:

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


$("input:unchecked")


回答4:

$("input[type='checkbox']:not(:checked):not('\#chkAll\')").map(function () { 
   var a = ""; 
   if (this.name != "chkAll") { 
      a = this.name + "|off"; 
   } 
   return a; 
}).get().join();

This will retrieve all unchecked checkboxes and exclude the "chkAll" checkbox that I use to check|uncheck all checkboxes. Since I want to know what value I'm passing to the database I set these to off, since the checkboxes give me a value of on.

//looking for unchecked checkboxes, but don’t include the checkbox all that checks or unchecks all checkboxes
//.map - Pass each element in the current matched set through a function, producing a new jQuery object containing the return values.

//.get - Retrieve the DOM elements matched by the jQuery object.
//.join - (javascript) joins the elements of an array into a string, and returns the string.The elements will be separated by a specified separator. The default separator is comma (,).


回答5:

You can use like this :

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


回答6:

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

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


回答7:

$(".clscss-row").each(function () {
if ($(this).find(".po-checkbox").not(":checked")) {
               // enter your code here
            } });