How to limit the amount of 'checkbox' selected?

Asked

Viewed 2,569 times

2

I have a form with 5 (five) checkbox. I wish the user could just dial 3 (three) of those 5 (five).

How do I do this validation using jQuery or Bootstrap?

Thanks to all for their cooperation.

1 answer

6

$(function(){
  var MAX_SELECT = 3; // Máximo de 'input' selecionados
  
  $('input.limited').on('change', function(){
    if( $(this).siblings(':checked').length >= MAX_SELECT ){
       this.checked = false;
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<p><strong>Selecione 3 opções:</strong></p>
<input class='limited' type='checkbox'/> Opção A <br>
<input class='limited' type='checkbox'/> Opção B <br>
<input class='limited' type='checkbox'/> Opção C <br>
<input class='limited' type='checkbox'/> Opção D <br>
<input class='limited' type='checkbox'/> Opção E <br>

Useful link: .sibilings

Browser other questions tagged

You are not signed in. Login or sign up in order to post.