Limit Number of Checkboxes Checked

后端 未结 5 1877
温柔的废话
温柔的废话 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 21:00

    Try (if your markup matches the one in the fiddle)

    jQuery(function(){
        var max = 3;
        var checkboxes = jQuery('input[type="checkbox"]');
    
        checkboxes.click(function(){
            var $this = $(this);
            var set = $this.add($this.prevUntil('label')).add($this.nextUntil(':not(:checkbox)'));
            var current = set.filter(':checked').length;
            return current <= max;
        });
    });
    

    Demo: Fiddle

    Update:
    Since you have a name for the checkboxes

    jQuery(function(){
        var max = 3;
        var checkboxes = jQuery('input[type="checkbox"]');
    
        checkboxes.click(function(){
            var $this = $(this);
            var set = checkboxes.filter('[name="'+ this.name +'"]')
            var current = set.filter(':checked').length;
            return current <= max;
        });
    });
    

    Demo: Fiddle

提交回复
热议问题