Check and validate the number of checked checkboxes using JavaScript
I check some checkboxes and would like the user to be able to select only 4 (out of 7 possible) and disable the rest if the current checkbox is checked (if there are already 3 checked) or enable all if the current checkbox is not checked. I really don't know where the problem is. This is my first experience with JavaScript ...
function verify_selected(selected_check_box_id) {
var count = 0;
var selected_check_boxes = new Array();
var check_boxes = new Array();
var inputs = document.getElementsByTagName("input");
for( var i in inputs ) {
if( inputs[i].type == "checkbox" ) check_boxes.push( inputs[i] );
}
// get current checkbox
for( var i in check_boxes ) if( check_boxes[i].id == selected_check_box_id ) var current_check_box = check_boxes[i];
var current_check_box_is_checked = current_check_box.checked;
// get all "checked"
for( var i in check_boxes ) {
if( check_boxes[i].checked ) {
selected_check_boxes.push( check_boxes[i] );
count += 1;
}
}
if( current_check_box_is_checked ) {
// checking
if( count < 4 ) {
current_check_box.checked = true;
// count = 4 - disabling
if( count == 4 ) {
for( var i in check_boxes ) {
if( !check_boxes[i].checked ) check_boxes[i].disabled = true;
}
}
}
else current_check_box.checked = false;
} else {
// unchecking
// count is < 4 -> enabling
for( var i in check_boxes ) {
check_boxes[i].disabled = false;
}
}
}
Any help is appreciated, thanks in advance.
a source to share
There were several mistakes. Let's give a good version first.
I also put a demo at http://jsbin.com/ajimi
function verify_selected(currentCheckbox) {
var count = 0;
var selected_check_boxes = []; // this will be fine...
var check_boxes [];
var inputs = document.getElementsByTagName("input");
for( var i in inputs ) {
if( inputs[i].type == "checkbox" ) check_boxes.push( inputs[i] );
}
// get all "checked"
for( var i in check_boxes ) {
if( check_boxes[i].checked ) {
count += 1;
}
}
if( currentCheckbox.checked && (count == 4)) {
for( var i in check_boxes )
if( !check_boxes[i].checked )
check_boxes[i].disabled = true;
} else {
for( var i in check_boxes )
check_boxes[i].disabled = false;
}
}
In the original version, you have a piece of code that looks like this:
if (count < 4) {
if (count == 4) {
Will not work. So this has been fixed.
As you saw in the other answer, we changed the function to pull the id. Instead of calculating the ID in some separate function (I'm assuming you are tracking the "last click" of some other function that occurs), just use this modifier to pass it to the function.
Ok, last but not least, what this will look like in jQuery. Hopefully this helps a little understanding of how it works and why it's worth using it:
(see example: http://jsbin.com/ihone )
function limitSelected(e) {
// get all of your checkboxes
var checkBoxes = $(e.currentTarget).parent().children().filter('input:checkbox');
// get the number of checkboxes checked, if 4, we'll disable
var disableCheckBoxes = (checkBoxes.filter(':checked').length == 4);
// enable checkboxes if we have < 4, disable if 4
checkBoxes.filter(':not(:checked)').each(function() {
this.disabled = disableCheckBoxes;
});
}
// when the document is ready, setup checkboxes to limit selection count
// if you have a particular div in which these checkboxes reside, you should
// change the selector ("input:checkbox"), to ("#yourDiv input:checkbox")
$(function() {
$('input:checkbox').click(limitSelected);
});
Another thing I will go over about this version is that it works with a group of checkboxes in a div, as opposed to your version, which will display checkboxes all over the page. (which is limiting.
a source to share
From a quick overview, your code seems too complex for the task.
Can I use something like jquery ? You can easily select the appropriate checkboxes using psudeo-selector ' : checked . Also, check out this tutorial .
If you don't want to use a library, I would suggest first creating a function that can count the number of checked boxes. Then create a feature that can disable or enable all unchecked checkboxes. Finally, combine the two and register a click event function for the checkboxes.
a source to share
As said cofiem
, your code looks pretty complicated for what you want to achieve; I recommend breaking it down into several smaller functions to make your code reusable and less complex.
First, create a function to get all the checkboxes on the page:
function getCheckboxes()
{
var inputs = document.getElementsByTagName("input");
var checkboxes = new Array();
for(var i=0;i<inputs.length;++i) {
if(inputs[i].type=="checkbox")
checkboxes.push(inputs[i]);
}
return checkboxes;
}
Then the function to enable / disable the checkboxes:
function setDisabled(state) {
var checkboxes = getCheckboxes();
for(i=0;i<checkboxes.length;++i) {
//Only unchecked checkboxes will need to be enabled/disabled
if(!checkboxes[i].checked)
checkboxes[i].disabled = state;
}
}
Now execute your function to check if the checkboxes need to be enabled or disabled:
function verify_selected(checkbox) {
var checkboxes = getCheckboxes();
var count=0;
for(i=0;i<checkboxes.length;++i) {
if(checkboxes[i].checked)
count++;
}
if(count>=4)
setDisabled(true);
else
setDisabled(false);
}
I changed the function declaration to pass the actual checkbox object and not the identifier string; it's much easier to call it a function:
<input type="checkbox" onClick="verify_selected(this);">
//Insert 7 of these..
As you can see, the code is much easier to read and maintain, and much less complex.
a source to share