check/uncheck bootstrap checkboxes with jQuery

I think you are looking for code like:

$(document).ready(function()
{
    $("#allstates").on("change", function()
    {
        var checked = $(this).prop("checked");

        $(this).parents(".controls")
            .first()
            .find("input[type=checkbox]")
            .prop("checked", checked);
    });
});

JsFiddle Example

When the state of the checkbox with the id allstates changes, get the checkbox value, find the first parent html element with a class called controls and then only update all the checkboxes in that element with the value of checked.


Also it is important to add prop to true on selecting checkboxes:

$("#checkAll").click(function(){
   var check = $(this).prop('checked');
   if(check == true) {
     $('.checker').find('span').addClass('checked');
     $('.checkbox').prop('checked', true);
   } else {
     $('.checker').find('span').removeClass('checked');
     $('.checkbox').prop('checked', false);
   }
});

Since I mentioned that this function checked all the checkboxes I had (even though the ones that were not supposed to be checked), I've been trying to look for the solution:

$('#allstates').click(function() {
  $('.checkbox').find('span').addClass('checked');
});

But this is not what I wanted. I mentioned also that I noticed that the code was "different" when inspecting it (in Chrome with F12). So as @thecbuilder said, it changes in order to add style.

I realized that since code is changing... I had to change the class (checkbox) from which I was starting the "span tag" search, so I change class checkbox to id states and this is the result:

$('#allstates').click(function() {
  if($(this).attr("checked")){
    $('#states').find('span').addClass('checked');        
  }else{
    $('#states').find('span').removeClass('checked');
  }    
});

Now it finally works.


Simple bootstrap checkbox

<label><input type="checkbox" value="">Option 1</label>

When debug in Chrome dev tool, label look like https://tinker.press/images/bootstrap-checkbox-label-2017-01-17_084755.png

To toogle checkbox state just set true|false on lable.control.checked

label.control.checked = false; //uncheck
label.control.checked = true; //check

Video demo https://youtu.be/3qEMFd9bcd8