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.