Limiting radio button selection across groups

2019-07-25 01:55发布

问题:

I know how to limit the number of checkboxes a user can choose, but am lost on how to do this with multiple groups of radio buttons.

This is the scenario. The first set of radio buttons allows the user to select a number - anything from 1 to 6. I am getting that value like this:

    $('#input_3_1 input').on('change', function() {
    var selectedVal = "";
    var selected = $("#input_3_1 input[type='radio']:checked");
    if (selected.length > 0) {
        selectedVal = selected.val();
    }
    });  

After that there are a series of radio groups, each with multiple options, like so:

    <div id="input_3_2" class="limit-this">
    <input name="input_2" type="radio" value="Choice 1">
    <input name="input_2" type="radio" value="Choice 2">
    <input name="input_2" type="radio" value="Choice 3">
    </div>

    <div id="input_3_3" class="limit-this">
    <input name="input_3" type="radio" value="Choice 1">
    <input name="input_3" type="radio" value="Choice 2">
    <input name="input_3" type="radio" value="Choice 3">
    </div>

And so on for a variable number of fields, which can be up to 10.

I need the user to by able to select only the number of choices selected in the first field across ALL of these other fields.

Can anyone point me in the right direction here?

回答1:

$('.limit-this input[type="radio"]').click(function(){
    var a = $('.limit-this input[type="radio"]:checked').length;
    if(a>selectedVal) if($(this).is(':checked')) $(this).removeAttr('checked');
});

See the DEMO

In DEMO2 I have enabled unchecking currently checked items for the case user changes his mind and wants to make another selection:

$('.limit-this input[type="radio"]').click(function(){
    var a = $('.limit-this input[type="radio"]:checked').length;
    var b = ($(this).is(':checked')?1:0);
    if(a>selectedVal){ if($(this).is(':checked')){ $(this).removeAttr('checked');}}
    else{

     if($(this).is(':checked')&&$(this).data('val')==1) {$(this).removeAttr('checked');
         $(this).data('val', 0);  
     }else
       $(this).data('val', b);    
    }

});