DEV Community

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

Posted on • Edited on

3 3

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

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay