"jQuery Checkbox Buttons"
Bootstrap 3.0.3 Snippet by mannack

<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="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <!------ Include the above in your HEAD tag ----------> <div class="container"> <br /> <!-- All colors --> <span class="button-checkbox"> <button type="button" class="btn" data-color="default">CS</button> <input type="checkbox" class="hidden" checked /> </span> <span class="button-checkbox"> <button type="button" class="btn" data-color="primary">MX</button> <input type="checkbox" class="hidden" checked /> </span> <span class="button-checkbox"> <button type="button" class="btn" data-color="success">GB</button> <input type="checkbox" class="hidden" checked /> </span> <span class="button-checkbox"> <button type="button" class="btn" data-color="info">OR</button> <input type="checkbox" class="hidden" checked /> </span> <span class="button-checkbox"> <button type="button" class="btn" data-color="warning">VT</button> <input type="checkbox" class="hidden" checked /> </span> <span class="button-checkbox"> <button type="button" class="btn" data-color="danger">Danger</button> <input type="checkbox" class="hidden" checked /> </span> <span class="button-checkbox"> <button type="button" class="btn" data-color="link">Link</button> <input type="checkbox" class="hidden" checked /> </span> </div>
$(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() .addClass('state-icon ' + settings[$button.data('state')].icon); // Update the button's color if (isChecked) { $button .removeClass('btn-default') .addClass('btn-' + color + ' active'); } else { $button .removeClass('btn-' + color + ' active') .addClass('btn-default'); } } // Initialization function init() { updateDisplay(); // Inject the icon if applicable if ($button.find('.state-icon').length == 0) { $button.prepend('<i class="state-icon ' + settings[$button.data('state')].icon + '"></i> '); } } init(); }); });

Related: See More


Questions / Comments: