形成多个复选框,其中包含可以选择的数量的限制

形成多个复选框,其中包含可以选择的数量的限制

问题描述:

I am having an issue with a form that I need to get the user to select a maximum of 2 checkbox and then it will then not let you select another one until you de-select one first I have got this working here https://jsfiddle.net/Ly1h825h/

But when the form is select I am not able to get the values for which ones have been ticked as the name of the checkbox are the same else the javascript will not work. So when I add the square brackets on the name so it becomes option[] this breaks the max limit on the checkbox you can select ie you can select all 4. which you can see in this example. https://jsfiddle.net/9tnwz8j2/

Can anyone see a way to fix this or something am doing wrong?

<form name="addtobasket50" id="addtobasket50" method="post" enctype="multipart/form-data" action="cart.php">
<label for="12345" id="select12345" class="inpSelect"><input type="checkbox" name="option[]" value="12345" id="12345" class="bundleChk" /> Select</label>
<label for="12346" id="select12346" class="inpSelect"><input type="checkbox" name="option[]" value="12346" id="12346" class="bundleChk" /> Select</label>
<label for="12347" id="select12347" class="inpSelect"><input type="checkbox" name="option[]" value="12347" id="12347" class="bundleChk" /> Select</label>
<label for="12348" id="select12348" class="inpSelect"><input type="checkbox" name="option[]" value="12348" id="12348" class="bundleChk" /> Select</label>
</form>
<script type="text/javascript">
function checkboxlimit(checkgroup, limit, bundleID){
    var checkgroup=checkgroup
    var limit=limit
    for (var i=0; i<checkgroup.length; i++){
        checkgroup[i].onclick=function(){
        var checkedcount=0
        for (var i=0; i<checkgroup.length; i++)
            checkedcount+=(checkgroup[i].checked)? 1 : 0
        if (checkedcount==limit) {
            document.getElementById('cart'+bundleID).disabled = false;
        }
        if (checkedcount>limit){
            //var prodID = this.checked.value;
            //alert(document.getElementsByName("option").checked);

            this.checked=false
            }
        }
    }
}
<script>
<script type="text/javascript">
checkboxlimit(document.forms.addtobasket50.option[], 2,50)
<script>

Thanks in advance Shuka

When you use dot notation to access properties, the property name must be a valid identifier, but [] is not part of a valid identifier (brackets are used to index into arrays and objects). To refer to a property whose name is not an identifier, you have to use array notation instead, with the property name as a literal string, so it should be:

checkboxlimit(document.forms.addtobasket50["option[]"], 2,50);