Question

I have 3 check-boxes with name="ItemGrp1" and 4 check-boxes with name="ItemGrp2".

Only 1 box can be checked from ItemGrp1 and only 2 maximum from ItemGrp2. A total of maximum 3 check-boxes can be checked.

I need to stop the user from ticking check-boxes if the user ticks more than total 3 check-boxes and also stop if user checks more than 1 from ItemGrp1 and more than 2 from ItemGrp2.

The names ItemGrp1/ItemGrp2 mentioned here are retrieved from a database and can be variable, so they should not be selected directly by name in jQuery.

My current HTML:

<input name="ItemGrp1" type="checkbox" value="10" />
<input name="ItemGrp1" type="checkbox" value="20" />
<input name="ItemGrp1" type="checkbox" value="30" />

<input name="ItemGrp2" type="checkbox" value="40" />
<input name="ItemGrp2" type="checkbox" value="50" />
<input name="ItemGrp2" type="checkbox" value="60" />
<input name="ItemGrp2" type="checkbox" value="70" />

And in Javascript:

var val_arr = [];

$("input[name^=ItemGrp]").change(function () {

    var CBVal = $(this).val();
    if ($(this).is(':checked')) {
        if (val_arr[CBVal] != 'A') {
            val_arr[CBVal] = 'A';
        }
    }
});

UPDATE

I am trying to use an array, then check if a checkbox is checked , if yes, then set the index to the checkbox value and value of that index to 'A', and then check the total count of the array. But the problem is that the length of the array comes out to be erroneous.

Was it helpful?

Solution

You can set a custom data-max attribute on each input field, which is filled through the database:

<input 
   name="<?php echo $field["name"]; ?>" 
   type="checkbox" value="<?php echo $field["value"]; ?>" 
   data-max="<?php echo $field["max_checked"]; ?>" 
/>

Then you can use the following checks in your javascript event handler:

$("input[type=checkbox]").change(function () {

  var InputName = $(this).attr("name");
  var MaxAllowed = $(this).attr("data-max");

   // Get amount of checked boxes with the same name
   if( $("input[name=" + InputName  + "]:checked").length >= MaxAllowed ){

       // Disable the remaining checkboxes of the same name
       $("input[name=" + InputName  + "]").not(":checked").attr("disabled", "disabled");

   } else {

       // Enable the inputs again when he unchecks one
       $("input[name=" + InputName  + "]").removeAttr("disabled");

});

OTHER TIPS

Separate the inputs with a div

<div class="grp1_div">
<input name="ItemGrp1" type="checkbox" value="10" />
<input name="ItemGrp1" type="checkbox" value="20" />
<input name="ItemGrp1" type="checkbox" value="30" />
</div>
<div class="grp1_div">
<input name="ItemGrp2" type="checkbox" value="40" />
<input name="ItemGrp2" type="checkbox" value="50" />
<input name="ItemGrp2" type="checkbox" value="60" />
<input name="ItemGrp2" type="checkbox" value="70" />
</div>

then you can call

$(".grp1_div input:checked").length


$(".grp2_div input:checked").length

Try this http://jsfiddle.net/SMCR8/

Use the new .prop() function:

$('.myCheckbox').prop('checked', true);
$('.myCheckbox').prop('checked', false);

JS :

var limititem1 = 1;
var limititem2 = 2;
var val_arr = [];



$("input[name^=ItemGrp]").change(function () {


  //dont check if total reached
if( $("input[name^=ItemGrp]:checked").length > ( limititem1+limititem2))
 {
     $(this).prop('checked', false);   
 }else
 //dont check if (ItemGrp1) and max reached
if( $(this).attr('name') == 'ItemGrp1' && $("input[name^=ItemGrp1]:checked").length > limititem1)
{
   $(this).prop('checked', false);      
}else
//dont check if ( ItemGrp2) and max reached
if ( $(this).attr('name') == 'ItemGrp2' && $("input[name^=ItemGrp2]:checked").length > limititem2)
{
   $(this).prop('checked', false);      
}else
//free to go 
{


    var CBVal = $(this).val();
    if ($(this).is(':checked')) {
        if (val_arr[CBVal] != 'A') {
            val_arr[CBVal] = 'A';
        }
    }
}
});

HTML :

<input name="ItemGrp1" type="checkbox" value="10" />
<input name="ItemGrp1" type="checkbox" value="20" />
<input name="ItemGrp1" type="checkbox" value="30" />
<input name="ItemGrp2" type="checkbox" value="40" />
<input name="ItemGrp2" type="checkbox" value="50" />
<input name="ItemGrp2" type="checkbox" value="60" />
<input name="ItemGrp2" type="checkbox" value="70" />

Can you try this here?

You can extend the conditions and limits with minimal changes in script. It is also possible to make it a JSON array to represend your configuration if you have a long list of these.

$(function(){ $('input[name="ItemGrp1"],input[name="ItemGrp2"]').change(function (e) {

    var currentGrp=$(this).attr('name');

    var alreadyChecked=$('input[name="'+currentGrp+'"]:checked').length;
    debugger;
    if($(this).is(':checked'))
        alreadyChecked--;

    if(currentGrp=='ItemGrp1'&&alreadyChecked==1&&$(this).is(':checked'))
        $(this).removeAttr('checked');
    else if(currentGrp=='ItemGrp2'&&alreadyChecked==2&&$(this).is(':checked'))
        $(this).removeAttr('checked');

});

});

$("input[name=ItemGrp1]").change(function(){
    if ($("input[name=ItemGrp1]:checked").length >0){
        $("input[name=ItemGrp1]").not(':checked').prop('disabled',true)
    }else{
        $("input[name=ItemGrp1]").prop('disabled',false)}
   });

  $("input[name=ItemGrp2]").change(function(){
    if ($("input[name=ItemGrp2]:checked").length >1){
        $("input[name=ItemGrp2]").not(':checked').prop('disabled',true)
    }else{
        $("input[name=ItemGrp2]").prop('disabled',false)}
   });

DEMO

may be this useful

<input class="one" name="ItemGrp1" type="checkbox" value="10" />
<input class="one" name="ItemGrp1" type="checkbox" value="20" />
<input class="one" name="ItemGrp1" type="checkbox" value="30" />
<input class="two" name="ItemGrp2" type="checkbox" value="40" />
<input class="two" name="ItemGrp2" type="checkbox" value="50" />
<input class="two" name="ItemGrp2" type="checkbox" value="60" />
<input class="two" name="ItemGrp2" type="checkbox" value="70" />

below jquery

$( ".one" ).on( "change", function() {      
    if(this.checked)
    {
        $(".one").each(function () {
            this.checked=false;            
        });
        this.checked =true;
    }   
});

$( ".two" ).on( "change", function() {   
    if (+$("input[name=ItemGrp2]:checked").length > 2)
    {
        this.checked=false;
    }             
});

Demo

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top