kylex
kylex

Reputation: 14406

Checkboxes always return checked whether they are or not

The HTML:

<div id="appcheck">
  <input class="precheck" type="checkbox" /> 
  <input class="precheck" type="checkbox" />
  <input class="precheck" type="checkbox" />
</div>

The jQuery that is supposed to discover unchecked results. Always returns 3 not checked no matter how many boxes are checked.

$('input.precheck').each(function() {
  if($(this).not(':checked')) {
    console.log('not checked');
  }
});

Upvotes: 2

Views: 92

Answers (1)

Ram
Ram

Reputation: 144739

You can use is + negation operator instead of not. not doesn't return a boolean value; it returns a jQuery object and your if statement is always true.

if (!$(this).is(':checked')) {

or:

if (!this.checked) {

You can also code:

var notChecked = $('input.precheck').filter(function(){
   return !this.checked;
}).length;

Upvotes: 5

Related Questions