Skip to content
Advertisement

Jquery loop over checkbox and check for non checked

I am wanting to loop over an checkbox input and check if the checkbox ISNT selected then add the value of the checkbox to an array which im wanting to POST through ajax.

I have an example below of looping through checkboxes which are selected but how would i do the inverse of this while still including the .each?

var categories = [];

$("input[name='categories[]']:checked").each(function () {
  categories.push(this.value);
});

Advertisement

Answer

You mean this?

$("input[name='categories[]']").each(function () {
  if (!this.checked) categories.push(this.value);
});

or

const categories = $("input[name='categories[]']").not(":checked")  // or ]:not(:checked)")
  .map(function() { return this.value })
  .get();
console.log(categories)  
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="categories[]" value="1" checked />
<input type="checkbox" name="categories[]" value="2" />
<input type="checkbox" name="categories[]" value="3" checked />
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement