0

I have 4 checkboxes: one "All" and three different element. The different elements has a class, the "All" checkbox has an id. I want to make checked the "All" checkbox if not checked any other elements. I made this code but not working (Mind means All)

$(document).ready(function() {
  $('#check-nemek-mind').click(function() {
    $('.check-nemek').prop('checked', false);
    $('#check-nemek-mind').prop('checked', true);
  });
  $('.check-nemek').click(function() {
    $('#check-nemek-mind').prop('checked', false);
    if (document.getElementByClass('check-nemek').checked) {} else {
      $('#check-nemek-mind').prop('checked', true);
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="checkbox">
  <label><input type="checkbox" id="check-nemek-mind" rel="nemek-mind" checked /><strong>Mind</strong></label>
</div>
<div class="checkbox">
  <label><input type="checkbox" class="check-nemek" rel="nemek-noi"/>Női divat</label>
</div>
<div class="checkbox">
  <label><input type="checkbox" class="check-nemek" rel="nemek-ferfi"/>Férfi divat</label>
</div>
<div class="checkbox">
  <label><input type="checkbox" class="check-nemek" rel="nemek-gyerek"/>Gyerek divat</label>
</div>
Calvin Nunes
  • 6,376
  • 4
  • 20
  • 48
shouldphp
  • 43
  • 5
  • Did you checked you console for errors? There's some of them that you should take a look – Calvin Nunes Aug 26 '19 at 19:08
  • 2
    Possible duplicate of [How to check whether a checkbox is checked in jQuery?](https://stackoverflow.com/questions/901712/how-to-check-whether-a-checkbox-is-checked-in-jquery) – devlin carnate Aug 26 '19 at 19:08

1 Answers1

1
document.getElementByClass('check-nemek').checked

change to

$('.check-nemek').is(':checked')

The reason we'd change this is because:

  1. There is no getElementByClass on the document object - you're looking for getElementsByClassName

  2. If we did switch to the proper getElementsByClassName - it would return a list of all the elements that matched our search - we'd then need to iterate that list to look for the 'check' status

  3. We'd probably want to switch to use JQuery since all other DOM interactions are using it.

  4. JQuery wraps the elements being returned in a JQuery wrapper which gives us access to helper methods, such as ".is(':checked')" - this will check across the returned list without us needing to write the iteration code.

Kyle
  • 1,463
  • 1
  • 12
  • 18
  • 1
    In addition to the code change itself, it would be helpful is this answer included an explanation of how this change solves the problem. – Wyck Aug 26 '19 at 19:32