"jQuery Checkbox Buttons"
Bootstrap 3.0.3 Snippet by RyanMasterson

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//netdna.bootstrapcdn.com/bootstrap/3.0.3/js/bootstrap.min.js"></script>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<!------ Include the above in your HEAD tag ---------->
<div class="container">
<h3>jQuery Checkbox Buttons<br />
<small>Buttons that change the state of their own hidden checkboxes, and vice-versa!</small>
</h3>
<br />
<span class="button-checkbox">
<button type="button" class="btn" data-color="primary">Unchecked</button>
<input type="checkbox" class="hidden" />
</span>
<span class="button-checkbox">
<button type="button" class="btn" data-color="primary">Checked</button>
<input type="checkbox" class="hidden" checked />
</span>
<hr />
<!-- All colors -->
<span class="button-checkbox">
<button type="button" class="btn" data-color="default">Default</button>
<input type="checkbox" class="hidden" checked />
</span>
<span class="button-checkbox">
<button type="button" class="btn" data-color="primary">Primary</button>
<input type="checkbox" class="hidden" checked />
</span>
<span class="button-checkbox">
<button type="button" class="btn" data-color="success">Success</button>
<input type="checkbox" class="hidden" checked />
</span>
<span class="button-checkbox">
<button type="button" class="btn" data-color="info">Info</button>
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
$(function () {
$('.button-checkbox').each(function () {
// Settings
var $widget = $(this),
$button = $widget.find('button'),
$checkbox = $widget.find('input:checkbox'),
color = $button.data('color'),
settings = {
on: {
icon: 'glyphicon glyphicon-check'
},
off: {
icon: 'glyphicon glyphicon-unchecked'
}
};
// Event Handlers
$button.on('click', function () {
$checkbox.prop('checked', !$checkbox.is(':checked'));
$checkbox.triggerHandler('change');
updateDisplay();
});
$checkbox.on('change', function () {
updateDisplay();
});
// Actions
function updateDisplay() {
var isChecked = $checkbox.is(':checked');
// Set the button's state
$button.data('state', (isChecked) ? "on" : "off");
// Set the button's icon
$button.find('.state-icon')
.removeClass()
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Related: See More


Questions / Comments: