Max 2 grup seçme

by borayeris

HTML

<p>Max 2 Gruptan seçilebilir</p>
 <div class="grup">
   <p><strong>Grup 1</strong></p>
   <input type="checkbox" class="grup1" name="grup1[]" value="1">1<br>
   <input type="checkbox" class="grup1" name="grup1[]" value="2">2<br>
   <input type="checkbox" class="grup1" name="grup1[]" value="3">3<br>
</div>
 <div class="grup">
   <p><strong>Grup 2</strong></p>
   <input type="checkbox" class="grup2" name="grup2[]" value="a">a<br>
   <input type="checkbox" class="grup2" name="grup2[]" value="b">b<br>
   <input type="checkbox" class="grup2" name="grup2[]" value="c">c<br>
</div>
 <div class="grup">
   <p><strong>Grup 3</strong></p>
   <input type="checkbox" class="grup3" name="grup3[]" value="?">?<br>
   <input type="checkbox" class="grup3" name="grup3[]" value="!">!<br>
   <input type="checkbox" class="grup3" name="grup3[]" value="&">&<br>
</div>
 <div class="grup">
   <p><strong>Grup 4</strong></p>
   <input type="checkbox" class="grup4" name="grup4[]" value="A">A<br>
   <input type="checkbox" class="grup4" name="grup4[]" value="B">B<br>
   <input type="checkbox" class="grup4" name="grup4[]" value="C">C<br>
</div>

JavaScript

$(function(){
    $('input[type="checkbox"]').on('click',function(){
        var $this = $( this );
        var thisClassName = $this.attr('class');
        
        var selectedGrups = [];
        $('.grup').each(function( i ){
            var grupClass = $('input[type="checkbox"]', this).first().attr('class');
            var grupCount = $('input.'+ grupClass +'[type="checkbox"]:checked').length;
            if( grupCount > 0	){
                selectedGrups.push( grupClass );
            }
            
        });
        
        //alert( $('input.'+ className +'[type="checkbox"]:checked').length )
        
        console.log( selectedGrups );
		
        if( selectedGrups.length == 2 ){
            var notClasses = [];
            $.each( selectedGrups, function( key, grupClassName ){
                
                notClasses.push( ':not(.'+ grupClassName +')' );
				
			});
			
			$('input[type="checkbox"]'+notClasses.join('') ).prop( 'disabled', true );
            console.log( 'input[type="checkbox"]'+notClasses.join() );
		}else if( selectedGrups.length < 2 ){
            $('input[type="checkbox"]').prop( 'disabled', false);
        }
    });
});