DEV Community

Cover image for Bootstrap + JQuery - How to create a checkbox button
Sandro Jhuliano Cagara
Sandro Jhuliano Cagara

Posted on • Edited on

Bootstrap + JQuery - How to create a checkbox button

Image description
HTML:

<div class="container p-4">
    <span class="button-checkbox">
        <button type="button" class="btn btn-sm btn-outline-primary" data-color="primary">Example</button>
          <input type="checkbox" class="d-none"/>
    </span>
</div>
Enter fullscreen mode Exit fullscreen mode

Script:

$('.button-checkbox').each(function () {
    var $button = $(this).find('button'),
        $checkbox = $(this).find('input:checkbox'),
        color = $button.data('color');

    $button.on('click', function () {
        $checkbox.prop('checked', !$checkbox.is(':checked')).triggerHandler('change');
        initialize();
    });

    $checkbox.on('click', function () {
        initialize();
    });

    function initialize() {
        var tab = $button.parents('.tab-pane').attr('id'),
            parentButton = $('#' + tab + '-tab'),
            checkBoxCount = $button.parents('.content').find('input[type="checkbox"]').filter(':checked').length,
            isChecked = $checkbox.is(':checked');

        $button.data('state', isChecked ? 'on' : 'off');
        parentButton.children('span').remove();

        if (checkBoxCount) {
            parentButton.append('<span class="badge badge-primary ml-auto float-right d-flex align-items-center shadow-sm">' + checkBoxCount + '</span>');
        }

        if (isChecked) {
            $button.append('<i class="fas fa-check ml-1"></i>');
            return $button.removeClass('btn-outline-primary').addClass('bg-' + color + ' shadow-sm text-white');
        }

        $button.children('i').remove();
        return $button.removeClass('bg-' + color + ' active text-white').addClass('btn-outline-primary');
    }
});

Enter fullscreen mode Exit fullscreen mode

Top comments (0)