0

First, I have a set of checkbox elements, i want that every time i click on it there's a way to count how many checkboxes where active inside the form. Next, place a limit on how many checkboxes I want to check, if it reaches the limit then I want the remaining checkboxes disabled. Currently, jquery .length returns the total number of checkboxes.

btw, i'm using a custom javascript/css checkbox, but i think the idea is the same

Harvey Katrina
  • 898
  • 1
  • 8
  • 14

3 Answers3

1

In order to retrieve the number of checked checkboxes, .length works but on the selector input:checked :

var nbChecked = $("input:checked").length;

In order to limit the number of checked boxes, you have to bind change event to your checkboxes and prevent click when this number is reached...

Working jsFiddle : http://jsfiddle.net/wpMzY/

Samuel Caillerie
  • 8,259
  • 1
  • 27
  • 33
0

If you pasted the code you already have - we could advise further.

Community
  • 1
  • 1
Jason
  • 560
  • 3
  • 10
  • 25
0

Full code example of what Samuel has answered, along with the option to allow the user to deselect his current option and pick a different option:

var maxAmountChecked = 3;

$('input[type=checkbox]').change(function(){
   if( $('input:checked').length > maxAmountChecked-1 ){
       //disable all unchecked checkboxes, keeping checked boxes available to deselect
       $('input:checkbox:not(:checked)').attr('disabled', 'disabled');
   }else{
       //if maximum amount is not reached, all checkboxes should be available
       $('input[type=checkbox]').removeAttr("disabled");
   }
});
Praxis Ashelin
  • 5,137
  • 2
  • 20
  • 46