mardi 24 novembre 2015

Restricting the number of checkboxes that can be selected

I am trying to restrict the number of checkboxes that can be selected to 3. The code below works but I would like to restrict it to the div class pricing-levels-3 containing the checkboxes.

HTML:

 <div class="pricing-levels-3">
      <p><strong>Which level would you like? (Select 3 Levels)</strong></p>
      <input class="single-checkbox"type="checkbox" name="vehicle" value="Bike">Level 1<br>
      <input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 2<br>
      <input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 3<br>
      <input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 4<br>
      <input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 5<br>
      <input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 6<br>
      <input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 7<br>
    </div>

jQuery

$('input[type=checkbox]').change(function(e){
if ($('input[type=checkbox]:checked').length > 3) {
    $(this).prop('checked', false)
    alert("allowed only 3");
}
})

Fiddle:




Aucun commentaire:

Enregistrer un commentaire