Toggle Button Checkebox

Toggle Button Checkebox

by Hilarius Doren

HTML

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.2/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-2.2.2.min.js"></script>
<div class="row">
                    <div class="col-sm-4 col-xs-12">
                        <p class="font-weight-bold">Bonnet</p>
                        <div data-toggle="buttons">
                            <label class="btn btn-block btn-success">
                                <input type="checkbox" name="oil" checked="checked" autocomplete="off"> Oil
                            </label>
                            <label class="btn btn-block btn-success">
                                <input type="checkbox" name="coolant" checked="checked" autocomplete="off"> Coolant
                            </label>
                            <label class="btn btn-block btn-success">
                                <input type="checkbox" name="breakfluid" checked="checked" autocomplete="off"> Break Fluid
                            </label>
                            <label class="btn btn-block btn-success">
                                <input type="checkbox" name="screenwash" checked="checked" autocomplete="off"> Screen Wash
                            </label>
                            <label class="btn btn-block btn-success">
                                <input type="checkbox" name="noleaks" checked="checked" autocomplete="off"> No Leaks
                            </label>
                        </div>
                    </div>
                    <div class="col-sm-4 col-xs-12">
                        <p class="font-weight-bold">Outside</p>
                        <div data-toggle="buttons">
                            <label class="btn btn-block btn-success">
                                <input type="checkbox" name="tyres" checked="checked" autocomplete="off">
                                Tyres
                            </label>
                            <label...

JavaScript

$('label.btn').on('click', function() {
            //Find the child check box.
            var $input = $(this).find('input');

            $(this).toggleClass('btn-danger btn-success');
            //Remove the attribute if the button is "disabled"
            if ($(this).hasClass('btn-danger')) {
                $input.removeAttr('checked');
            } else {
                $input.attr('checked', '');
            }

            return false; //Click event is triggered twice and this prevents re-toggling of classes
        });