Limiter le nombre de cases à cocher sélectionnées avec javascript et bootstrap

Published: 06 novembre 2017

DMCA.com Protection Status

Simple illustration de comment limiter le nombre de cases à cocher sélectionnées avec javascript (source) et de comment améliorer l'apparence avec bootstrap (source). Dans cet exemple on souhaite que l'utilisateur ne puisse sélectionner que deux cases au maximum (Note pour changer la limite il suffit d'éditer la ligne suivante: var limit = 2; dans le code complet ci-dessous).

Limiter le nombre de cases à cocher sélectionnées avec javascript et bootstrap
Limiter le nombre de cases à cocher sélectionnées avec javascript et bootstrap

Code complet:

<!DOCTYPE html>
<html lang="en">
<head>

<!-- sources: 
https://bootsnipp.com/snippets/featured/checked-list-group
http://jsfiddle.net/vVxM2/
--!>

  <title>How to limit the number of selected checkboxes?</title>

  <meta charset="utf-8">

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

  <style>
  body {
  padding-top: 50px;
  background-color:#FFFFF; 
  }
  </style>

</head>
<body>

<div class="container">

Please, select up to two options: <br><br>

<div class="row">       
    <div class="col-md-2">
    <div class="form-group ">
       <span class="button-checkbox">
        <button type="button" class="btn btn-block" data-color="primary">Option 1</button>
        <input  type="checkbox" class="hidden" />
        </span>
    </div>
    </div>                              
</div>

<div class="row">       
    <div class="col-md-2">
    <div class="form-group ">
       <span class="button-checkbox">
        <button type="button" class="btn btn-block" data-color="primary">Option 2</button>
        <input  type="checkbox" class="hidden" />
        </span>
    </div>
    </div>                              
</div>

<div class="row">       
    <div class="col-md-2">
    <div class="form-group ">
       <span class="button-checkbox">
        <button type="button" class="btn btn-block" data-color="primary">Option 3</button>
        <input  type="checkbox" class="hidden" />
        </span>
    </div>
    </div>                              
</div>

<div class="row">       
    <div class="col-md-2">
    <div class="form-group ">
       <span class="button-checkbox">
        <button type="button" class="btn btn-block" data-color="primary">Option 4</button>
        <input  type="checkbox" class="hidden" />
        </span>
    </div>
    </div>                              
</div>

<div class="row">       
    <div class="col-md-2">
    <div class="form-group ">
       <span class="button-checkbox">
        <button type="button" class="btn btn-block" data-color="primary">Option 5</button>
        <input  type="checkbox" class="hidden" />
        </span>
    </div>
    </div>                              
</div>

<div class="row">       
    <div class="col-md-2">
    <div class="form-group ">
       <span class="button-checkbox">
        <button type="button" class="btn btn-block" data-color="primary">Option 6</button>
        <input  type="checkbox" class="hidden" />
        </span>
    </div>
    </div>                              
</div>

</div>

<script>
$(function () {
$('.button-checkbox').each(function () {

    // Settings
    var $widget = $(this),
        $button = $widget.find('button'),
        $checkbox = $widget.find('input:checkbox'),
        color = $button.data('color'),
        settings = {
            on: {
                icon: 'glyphicon glyphicon-check'
            },
            off: {
                icon: 'glyphicon glyphicon-unchecked'
            }
        };

    // Event Handlers
    $button.on('click', function () {

        //alert($checkbox.is(':checked'));

        var limit = 2;
        if (document.querySelectorAll('input[type="checkbox"]:checked').length >= limit ){
            if ($checkbox.is(':checked')) {
                $checkbox.prop('checked', !$checkbox.is(':checked'));
                $checkbox.triggerHandler('change'); 
                updateDisplay();            
            }
        }    
        else {
            $checkbox.prop('checked', !$checkbox.is(':checked'));
            $checkbox.triggerHandler('change'); 
            updateDisplay();                               
        }

        //$checkbox.prop('checked', !$checkbox.is(':checked'));
        //$checkbox.triggerHandler('change'); 
        //updateDisplay();

    });
    $checkbox.on('change', function () {
        updateDisplay();
    });

    // Actions
    function updateDisplay() {
        var isChecked = $checkbox.is(':checked');

        // Set the button's state
        $button.data('state', (isChecked) ? "on" : "off");

        // Set the button's icon
        $button.find('.state-icon')
            .removeClass()
            .addClass('state-icon ' + settings[$button.data('state')].icon);

        // Update the button's color
        if (isChecked) {
            $button
                .removeClass('btn-default')
                .addClass('btn-' + color + ' active');
        }
        else {
            $button
                .removeClass('btn-' + color + ' active')
                .addClass('btn-default');
        }
    }

    // Initialization
    function init() {

        updateDisplay();

        // Inject the icon if applicable
        if ($button.find('.state-icon').length == 0) {
            $button.prepend('<i class="state-icon ' + 
            settings[$button.data('state')].icon + '"></i> ');
        }
    }
    init();
});
});
</script>

</body>
</html>

Références

Image

of