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>
Technically, the Twitter Bootstrap Buttons plugin is meant to work with <button>
elements and have them behave as though they were radio or checkbox inputs.
Also, $().button('toggle')
is just psuedo code, and in practice is meant to be used with a selector, e.g., $('.btn-toggle').button('toggle')
. However, your example is a bit substandard, since you have assigned classes intended for buttons to <label>
elements.
Anyway, despite all that, if all you want to do is set all your input boxes to true, you could use something like:
$('.btn-group input[type="checkbox"]').prop('checked', true);
If you wanted to do it with <button>
elements, it would be something like this:
However, that drops a bunch of the input data which you're working with.
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.
I found a way to do this without JS
http://codepen.io/ibanez182/pen/WxKABq/
<div class="form-group">
<div class="checkbox">
<label data-toggle="collapse" data-target="#collapseOne" aria-expanded="false" aria-controls="collapseOne">
<input type="checkbox"/> A checkbox
</label>
</div>
</div>
<div id="collapseOne" aria-expanded="false" class="collapse">
<div class="well">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Saepe ut molestias eius, nam neque esse eos modi corrupti harum fugit, hic recusandae praesentium, minima ipsa eligendi architecto at! Culpa, explicabo.</div>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With