Reputation: 564
I have this form with questions that uses checkboxes and radiobuttons, the checkbox questions can have a max amount of checked needed to go to the next question. For the checkboxes and radio buttons i am using the bootstrap buttons.
https://getbootstrap.com/docs/4.1/components/buttons/#checkbox-and-radio-buttons
I use jquery change function to see when something happens to the checkbox, when something changes i check how many are checked and compare it with the max amount. If the amount of checked is higher than the max then i uncheck the checkbox that was just checked. Problem with this is that when a checkbox unchecks it changes the checkbox and I get an infinite loop and end up getting the error "too much recursion".
Any clue on how I can make this work? I've tried .click instead of .change but then when I get the amount of checked it gives me the wrong number.
Script:
function checkboxHandler(aThis){
if($('.pro-block.pb-active').find('.proanalysecheck:checked').length > $(aThis).data('max')) {
if($(aThis).prop('checked') == true){
$(aThis).parent('label').button('toggle');
}
}
}
$('#frmProinvite .proanalysecheck').change( function(e) {
checkboxHandler(this);
});
.pb-block.pb-active
is the current question div and .proanalysecheck
is the input class.
Upvotes: 0
Views: 233
Reputation: 71
What about using a flag which indicates that a change is caused by reaching the max selections? This should do the job.
var changeByMaxReached = false;
function checkboxHandler(aThis){
if(!changeByMaxReached && $('.pro-block.pb-active').find('.proanalysecheck:checked').length > $(aThis).data('max')) {
if($(aThis).prop('checked') == true){
changeByMaxReached = true;
$(aThis).parent('label').button('toggle');
}
}
}
$('#frmProinvite .proanalysecheck').change( function(e) {
if (!changeByMaxReached) {
checkboxHandler(this);
}
changeByMaxReached = false;
});
Upvotes: 1