Limit Multi-Checkbox to "x" selections

Hi everyone,

I have a bunch of multi-checkboxes and each has a different amount of MAX selections allowed.
Does anyone know a simple code to limit the number of checked boxes? Looking for a simple code as I have about 50+ of these to do.

Appreciate any help. Thanks

Hi miguel.

There is a way but it ain’t easy.
What you have to do is:
onChange → check if selectedindices is not greater then the max selections.
if not greater → save the values of your checkboxgroup.
if greater → compare wich values are not the same.
then find the index of it.
then get the checkboxgroup selectedindices and slice them.
then add them back to the checkboxgroup

Oke so i tested somethings out a bit.
I found the solution how to do it kinda easy.

On the top of the page code add
var selectedIndices
var maxSelections = 4

Then in the onChange of your checkboxgroup add this code.

   if($w("#checkboxGroup1").selectedIndices.length > maxSelections ){
        $w("#text1").text = "can't add any more selections"
       $w("#checkboxGroup1").selectedIndices = selectedIndices
    } else {
        selectedIndices = $w("#checkboxGroup1").selectedIndices
        var count = maxSelections  - $w("#checkboxGroup1").selectedIndices.length
        if(count === 0){
            $w("#text1").text =`can't add any more selections`
        } else {
            $w("#text1").text =`u have still ${count} amount of selections`
        }
    }

This wil only let you select 4
Chenge the maxSelections to higher or lower the max selections.

the text1 element will show how many selections you have left
or display that there aren’t any left.

Hope this helps.

Kind regards,
kristof.

@volkaertskristof

Thank you. I’ll give it a try and reply back. Appreciate you taking time to send some help.

@volkaertskristof

Went with this option. Easier to adjust the max individually. Code Below.

let selectedIndices ;
$w . onReady ( function () {
$w ( “#checkboxGroup1” ). onChange (( event ) => {
if ( $w ( “#checkboxGroup1” ). value . length < 4 ){
//add a notification for the user
} else if ( $w ( “#checkboxGroup1” ). value . length === 4 ){
selectedIndices = $w ( “#checkboxGroup1” ). selectedIndices ;
} else if ( $w ( “#checkboxGroup1” ). value . length > 4 ){
$w ( “#checkboxGroup1” ). selectedIndices = selectedIndices ;
//add a notification for the user
}
})
});

Hi Miquel,
Nice to see that you adjustes it , it means you are understanding the code the way i did it :wink:

Sometimes its easyer to have a variable at the top to adjust them all at the same time, if you use it more then once you just have to change 1 piece of code and not all of it :slight_smile:

Anyway, happy i could help,
Have a nice weekend.

Kind regards,
Kristod