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

Active 06 novembre 2017    /    Viewed 2805    /    Comments 0    /    Edit


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

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

Liens Site
How to limit the number of selected checkboxes? stackoverflow
jsfiddle jsfiddle
bootsnipp bootsnipp
getbootstrap getbootstrap.com
bootstrap checkbox like button bootsnipp.com
Count the number of checked checkboxes in HTML stackoverflow
how to display variable value in alert box? stackoverflow
.on change vs .on click [duplicate] stackoverflow
jQuery checking a checkbox and triggering javascript onclick event stackoverflow
.prop() api.jquery.com
How do I check/uncheck a checkbox input or radio button? learn.jquery.com
jQuery .prop('checked', false) does not work stackoverflow
Check/Uncheck checkbox with JavaScript? stackoverflow
-How to check whether a checkbox is checked in jQuery? stackoverflow


Card image cap
profile-image
Daidalos

Hi, I am Ben.

I have developed this web site from scratch with Django to share with everyone my notes. If you have any ideas or suggestions to improve the site, let me know ! (you can contact me using the form in the welcome page). Thanks!