treehouse : what would you like to learn today?
Web Design Web Development iOS Development

[Solved] Toggle checkboxes [CodePen included]

  • I have a checkbox that when checked should toggle checkboxes in a form below.

    The function works perfectly on first iteration, however any time after that the checkboxes in the form are not checked.

    I've included a simplified version of my code in the CodePen below

    http://codepen.io/anon/pen/hldDI

  • Solved, simply replace the attr function with prop and it will work as expected.

  • Weirdest thing! Seems to me like a bug with setting checkboxes with attr('checked', ...);, you code should definitely be working. I found a workaround though, by simulating a click (also changed your code a bit so you can remove the onclick handler from your html)

    $(function() {
      var checkBoxes = $('.activity');
    
      $('#get-last-quarter').change(function() {
        var checked = $(this).prop('checked');
    
        checkBoxes.each(function() {
          var $this = $(this);
    
          if ($this.prop('checked') != checked)
            $this.click();
        });
      });
    })
    

    Edit: Ugh, I should refresh before submitting comments... xD Your solution is better.