0

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);
});
1
  • $("input[name='categories[]']:not(:checked)") Commented Aug 4, 2021 at 8:31

1 Answer 1

0

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 />

Sign up to request clarification or add additional context in comments.

1 Comment

But second solution is more elegant ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.