Posted By

del4y on 04/02/15


Tagged

javascript simple jquery checkbox custom


Versions (?)

simple custom checkboxes


 / Published in: jQuery
 

This is a simple way to make custom checkboxes in jQuery.

  1. /**
  2.  * Example:
  3.  *
  4.  * HTML:
  5.  * <button data-checkbox="state" data-value="1">ready</button>
  6.  * <button data-checkbox="state" data-value="2">busy</button>
  7.  *
  8.  * CSS:
  9.  * .active {
  10.  * background-color: red;
  11.  * }
  12.  */
  13.  
  14. $(document).ready(function(){
  15. initializeCheckBoxes();
  16. });
  17.  
  18. function initializeCheckBoxes() {
  19. var $checkboxes = $('[data-checkbox]');
  20.  
  21. for (var i = 0; i < $checkboxes.length; i++) {
  22. var $checkbox = $($checkboxes[i]);
  23. var id = $checkbox.data('checkbox') + '-' + i;
  24.  
  25. $checkbox.data('checkbox-id', id);
  26.  
  27. var $realCheckbox = $('<input type="checkbox" id="' + id + '" name="' + $checkbox.data('checkbox') + '" value="' + $checkbox.data('value') + '" style="display:none">');
  28. $realCheckbox.insertAfter($checkbox);
  29.  
  30. // Check if is selected
  31. if (parseInt($checkbox.data('checkbox-selected')) === 1 || $checkbox.hasClass('active')) {
  32. $realCheckbox.prop('checked', true);
  33. $checkbox.addClass('active');
  34. }
  35. }
  36.  
  37. $checkboxes.unbind('click').on('click', function () {
  38. var checkBoxId = $(this).data('checkbox-id');
  39. var $checkbox = $('#' + checkBoxId);
  40.  
  41. if ($checkbox.prop('checked')) {
  42. $(this).removeClass('active');
  43. $checkbox.removeProp('checked');
  44. } else {
  45. $(this).addClass('active');
  46. $checkbox.prop('checked', true);
  47. }
  48. });
  49. }

Report this snippet  

You need to login to post a comment.