MacAngus MacAngus - 4 months ago 23
Javascript Question

Toggle checkbox on Twitter Bootstrap

I made a group of checkboxes with Twitter Bootstrap. Now I would like to do a "select all" or "deselect all" button. How could I do this using a JS function?

The Twitter Bootstrap documentation says to use $().button('toggle') but it doesn't work.

Here is my code snippet:

<div class="control-group">
<div class="controls">
<div class="input">
<div class="btn-group">
<label class="btn btn-toggle" for="colors-1-toggle-0">
<input type="checkbox" id="colors-1-toggle-0" name="colors-1[]" value="color_c" />C
</label>
<label class="btn btn-toggle" for="colors-1-toggle-1">
<input type="checkbox" id="colors-1-toggle-1" name="colors-1[]" value="color_m" />M
</label>
<label class="btn btn-toggle" for="colors-1-toggle-2">
<input type="checkbox" id="colors-1-toggle-2" name="colors-1[]" value="color_y" />Y
</label>
<label class="btn btn-toggle" for="colors-1-toggle-3">
<input type="checkbox" id="colors-1-toggle-3" name="colors-1[]" value="color_k" />K
</label>
</div>
</div>
</div></div>

Answer

Thank you merv! Thanks to you I came to this solution:

<button id="toggle-colors" class="btn btn-info">Toggle</button>
<script>
    $('#toggle-colors').click(function() {
        $('.btn-group input[name^="colors"]').each(function(){
            // toggle checkbox
            $(this).prop('checked',!$(this).prop('checked'));
            // toggle class
            $(this).parents('label').toggleClass('active');
        });
    });
</script>

I don't use the button tag as Twitter Bootstrap recommends because it doesn't send the value per POST.