I am trying to make a function that will:
- run through all of the checkboxes I have checked in the html document
- only allow 'checkboxLimit' to be checked (i.e. 4 checkboxes out of the 10 can be checked in the document)
- return an array of the id's of the checked checkboxes (which I call cbl)
Currently, my issue has something to do with the scope of the onclick function.
function getCheckboxes(checkboxLimit) {
// clear cbl
cbl = ['','','',''];
// contstuct list of checkbox tags
inputs = document.getElementsByTagName('input');
var checkboxes = [];
for ( var i = 0 ; i < inputs.length ; i++ ) {
if (inputs[i].type == 'checkbox')
checkboxes.push(inputs[i]);
}
All of the code above is functional, but the code below is where I run into issues. The function that is executed after 'onclick' works nicely, because if I alert cbl in the function, it works as I like (shown below). However, once cbl is alerted after the 'onclick' function, it is no longer the same.
// construct list of checked checkboxes (limited)
for ( var i = 0 ; i < checkboxes.length ; i++ ) {
// if any checkbox is clicked
checkboxes[i].onclick = function() {
var checkCount = 0;
// run through each of the checkboxes
for ( var j = 0 ; j < checkboxes.length ; j++ ) {
// if index checkbox is checked
if ( checkboxes[j].checked == true ) {
// add to count
checkCount++;
// if count is above limit, uncheck
// otherwise add to list
if ( checkCount > checkboxLimit)
this.checked = false;
else
cbl[checkCount-1] = checkboxes[j].id;
}
}
// alert that displays cbl how I want
alert(cbl);
}
// alert that does not display cbl how I want
alert(cbl);
}
}
So is there some way I can get past this scope issue? I would prefer staying away from JQuery, but whatever can get me to have functional code will work at this point.
cblto be when it doesn't display how you want ?(function(i){checkbokes[i].onclick = function(){}})(i);or you'll be at the end of your loop, but that's not the behavior you're looking for anyways. I'm going to make you a function that will allow you to test for a max and minimum. Hold on.