Limit Number of Checkboxes Checked

后端 未结 5 1842
温柔的废话
温柔的废话 2021-01-14 20:16

I have a form with several checkboxes. I have three categories of checkboxes in the form. I need to limit to a max of three checkboxes per category.

I used

5条回答
  •  鱼传尺愫
    2021-01-14 20:56

    just add a class to all the related check boxes, and just use the class selector when checking the checkboxes for a category. eg:

    HTML

    
    
    
    
    
    
    
    
    
    ...
    

    JS

    jQuery(function(){
       var max = 3;
    
       var cat1_checkboxes = jQuery('input.cat1[type="checkbox"]');
       var cat2_checkboxes = jQuery('input.cat2[type="checkbox"]');
       var cat3_checkboxes = jQuery('input.cat3[type="checkbox"]');
    
    
       cat1_checkboxes.change(function(){
          var current = cat1_checkboxes.filter(':checked').length;
           checkboxes.filter(':not(:checked)').prop('disabled', current >= max);
       });
    
       cat2_checkboxes.change(function(){
          var current = cat2_checkboxes.filter(':checked').length;
           checkboxes.filter(':not(:checked)').prop('disabled', current >= max);
       });
    
       cat3_checkboxes.change(function(){
          var current = cat3_checkboxes.filter(':checked').length;
           checkboxes.filter(':not(:checked)').prop('disabled', current >= max);
       });
    
    });
    

提交回复
热议问题