Reputation: 15700
I can get all checked checkboxes with:
document.querySelectorAll('input[type=checkbox]:checked')
Is there a way to get the unchecked boxes?
Upvotes: 2
Views: 1348
Reputation: 31
I had the same issue, and trying to work out how to use it in my code - looking for multiple cases of checked/not checked/Jquery/not Jquery. Im not a javascript ninja - so in the end, it was a little more convoluted, but I wrote my own little routine. I pulled back everything using:
`var formData = $(':input');`
this pulled back ALL inputs checked/not checked/text/select - everything. The result was an array of objects stored in the var "formData".
With an array it has useful things like length/values etc that I could iterate through and look for the result.
`for( var i = 0; i < formData.length; i++){
if(formData[i].type === "checkbox"){
inputName = formData[i].name.toUpperCase();
inputValue = formData[i].checked === true ? "1" : "0" ;
`
You could even step over all other inputs like buttons etc with a line like:
`if( (inputs[i].nodeName === "INPUT" || inputs[i].nodeName === "SELECT") && inputs[i].type != "hidden" ){ `
Like I said - convoluted - but it works for me - and in a library I only needed to write it once..... I'm sure the purists out there will pull me up on it - but as I said - "it works for me"
If you need any more explanation, let me know.
Hope this helps.
Upvotes: 1
Reputation: 371193
You can use the not
psuedo-selector in combination with checked
:
console.log(
document.querySelectorAll('input[type=checkbox]:not(:checked)').length
);
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox" checked>
<input type="checkbox" checked>
Upvotes: 7