Bootstrap 3 - multiple active buttons with minimum one selected

I have these multiple selection buttons. What should I do so that the user cannot uncheck them all. There has to be at least one button selected, if not more:

<div class="container">
    <br><p>Click all the fruits that you like</p>
    <div class="btn-group col-xs-12" data-toggle="buttons">
        <label class="btn btn-default">
            <input type="checkbox" name="fruit" id="apple" value="apple">apple
        </label>
        <label class="btn btn-default">
            <input type="checkbox" name="fruit" id="pear" value="pear">pear
        </label>
        <label class="btn btn-default">
            <input type="checkbox" name="fruit" id="orange" value="orange">orange
        </label>
    </div>
</div>

Answers 1

  • Example: https://jsfiddle.net/o1jwc7h7/

    Add this jquery:

    $('.btn-group input[type="checkbox"]').change(function(){
        if ($('input[type="checkbox"]:checked').length == 0) {
           $(this).prop("checked",true).parent().addClass('active');
           alert("at least one of them should be checked");
        }
    });
    

Related Articles