/ Published in: jQuery
This is a simple way to make custom checkboxes in jQuery.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
/** * Example: * * HTML: * <button data-checkbox="state" data-value="1">ready</button> * <button data-checkbox="state" data-value="2">busy</button> * * CSS: * .active { * background-color: red; * } */ $(document).ready(function(){ initializeCheckBoxes(); }); function initializeCheckBoxes() { var $checkboxes = $('[data-checkbox]'); for (var i = 0; i < $checkboxes.length; i++) { var $checkbox = $($checkboxes[i]); var id = $checkbox.data('checkbox') + '-' + i; $checkbox.data('checkbox-id', id); var $realCheckbox = $('<input type="checkbox" id="' + id + '" name="' + $checkbox.data('checkbox') + '" value="' + $checkbox.data('value') + '" style="display:none">'); $realCheckbox.insertAfter($checkbox); // Check if is selected if (parseInt($checkbox.data('checkbox-selected')) === 1 || $checkbox.hasClass('active')) { $realCheckbox.prop('checked', true); $checkbox.addClass('active'); } } $checkboxes.unbind('click').on('click', function () { var checkBoxId = $(this).data('checkbox-id'); var $checkbox = $('#' + checkBoxId); if ($checkbox.prop('checked')) { $(this).removeClass('active'); $checkbox.removeProp('checked'); } else { $(this).addClass('active'); $checkbox.prop('checked', true); } }); }