I am trying to make a function that will:
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.
Try something more like this:
function checkboxValidate(collection, min, max){
var mn = typeof min === 'undefined' ? 0 : min;
var mx = typeof max === 'undefined' ? Infinity : max;
var cb = [], n = 0;
for(var i=0,l=collection.length; i<l, i++){
var c = collection[i];
if(c.type === 'checkbox' && c.checked){
cb.push(c); n++;
}
}
if(n < mn){
// somthing.innerHTML = 'Minimum Requirement Failure';
return false;
}
else if(n > mx){
// somthing.innerHTML = 'Maximum Requirement Failure';
return false;
}
else{
return cb;
}
}
anotherElement.onclick = function(){
var checkedArray = checkboxValidate(document.getElementsByTagName('input'), 0, 3));
if(checkedArray && checkedArray[0]){
// checkedArray has each checkbox Element - more properties than just `id`
}
else{
// checkedArray would be false or not have any checked with min 0
}
}
Adjust as needed.
A non cross-browser crude sample. Perhaps you can get something from it:
function limitCheck(n) {
var x = [];
document.addEventListener('click', function(e) {
var i, t = e.target;
if (t.type === 'checkbox') {
if ((i = x.indexOf(t.id)) > -1) {
console.log('remove ' + i + ', ' + t.id);
x.splice(i, 1);
} else if (x.length < n) {
x.push(t.id);
} else {
console.log('LIM');
e.preventDefault();
e.stopPropagation();
}
console.log(x);
}
});
}
limitCheck(4);
Without debug:
function limitCheck(n) {
var x = [];
document.addEventListener('click', function(e) {
var i, t = e.target;
if (t.type === 'checkbox') {
if ((i = x.indexOf(t.id)) > -1) {
x.splice(i, 1);
} else if (x.length < n) {
x.push(t.id);
} else {
e.preventDefault();
e.stopPropagation();
}
}
});
}
You can put a click listener on an ancestor of the checkboxes, probably they're in a form so use that. You also need to account for a reset button, and for buttons that are checked by default (so you also need to run the function on page load to pre-populate the list):
var checkboxLimit = 4;
var cbl;
function limitCheckboxes(form, event) {
// Clear checkbox list
var cblTemp = [];
// get element that the click came from
var tgt = event.target || event.srcElement;
// See if it was a reset
var reset = tgt.type == 'reset';
// Count checked checkboxes
// If click was from reset, reset the checkbox first
var cb, cbs = form.getElementsByTagName('input');
for (var i=0, iLen=cbs.length; i<iLen; i++) {
cb = cbs[i];
if (cb.type == 'checkbox') {
cb.checked = reset? cb.defaultChecked : cb.checked;
if (cb.checked) {
cblTemp.push(cb.id);
}
}
}
// If too many, remove the last one that was checked,
// uncheck it and show a message
if (cblTemp.length > checkboxLimit && tgt.type == 'checkbox') {
cblTemp.splice(cblTemp.indexOf(tgt.id), 1);
tgt.checked = false;
console.log('removed ' + tgt.id);
}
// update cbl
cbl = cblTemp;
// Debug
console.log(cbl);
}
You can also get the checked checkboxes in one go using querySelectorAll :
var cb, cbs = document.querySelectorAll('input[type="checkbox"]');
and the for loop is simpler:
for (var i=0, iLen=cbs.length; i<iLen; i++) {
cb = cbs[i];
cb.checked = reset? cb.defaultChecked : cb.checked;
if (cb.checked) {
cblTemp.push(cb.id);
}
}
It would be even better to use a class, so you can have other checkboxes that aren't part of the restricted set.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.