Streaming live at 10am (PST)

Limit number of selected checkboxes

Hi,

I have a form with checkboxes, and I’d like people to be able to check only 3 checkboxes, not all of them.
I figured javascript was needed for that and I found this code that I adapted with my classes

    <script>
$('.checkboxmetiers').on('change', function() {
   if($('.checkboxmetiers:checked').length > 3) {
       this.checked = false;
   }
});
</script>

I also added the right class to my input (I tried to put in on the checkbox, on the name, the two of them) but the script doesn’t work.
capture

Could anyone help?

Thanks!

Got a link to your published site page?

This should help you out. I have also added a visual cue to let your user know that they cant select more than 3 boxes;

<script>
    $(document).ready(function(){
        var $checkboxWrapper = $('div.checkboxmetiers');

        $checkboxWrapper.find('input[type=checkbox]').on('change', function() {
            if( $checkboxWrapper.find('input[type=checkbox]:checked').length > 3) {
                 $(this).prop('checked', false).change();
            }

            if( $checkboxWrapper.find('input[type=checkbox]:checked').length === 3) {
                $checkboxWrapper.find('input[type=checkbox]:not(:checked)').closest('label').css({'opacity': '0.5', 'pointer-events' : 'none'})
            } else {
                $checkboxWrapper.find('label').css({'opacity': '', 'pointer-events' : ''})
            }
        });
    })
</script>
1 Like

Oh my, it works delightfully! Thank you so much!

@Alegria

Very welcome. Glad it helped.

Hi @AlexManyeki !

Just wanted to take some time to thank you for the script! I had the same issue and it helped a lot!

Nico

That’s great @Nicolas_C1 .

All the best with your project.

Hi @AlexManyeki

Thank you for your code, But somehow i’m not manage to apply it in my project,
I’ll be happy if you could take a look

https://preview.webflow.com/preview/questionnaire-2?utm_medium=preview_link&utm_source=designer&utm_content=questionnaire-2&preview=0efbe5c3381e2b35f3125bc76ee0d64f&mode=preview

Hey @Tene_Lisi

You will need to replace the checkbox wrapper’s class with your own. So replace this line;

v̶a̶r̶ ̶$̶c̶h̶e̶c̶k̶b̶o̶x̶W̶r̶a̶p̶p̶e̶r̶ ̶=̶ ̶$̶(̶'̶d̶i̶v̶.̶c̶h̶e̶c̶k̶b̶o̶x̶m̶e̶t̶i̶e̶r̶s̶'̶)̶;̶

with

var $checkboxWrapper = $('div.form-item-wrapper');

Working great, I thought at first that it’s need to be on the checkbox class.
Thanks a lot! also for your fast respond

1 Like

Hi!

I came across this post which seems to be beneficial to everyone else, but I can’t seem to figure it out. Is there someone that could help me?

Here is my read-only link: Webflow - JCares