Roby Sottini Roby Sottini - 1 month ago 9
HTML Question

How to count items in HTML name array attribute?

I have 3 checkboxes and the user can only select 1 or 2 of them. If the user select 3 checkbox, I will show a message with jQuery saying "You can't select 3 items".

<input type="checkbox" value="Walk" name="sports[]">
<input type="checkbox" value="Swim" name="sports[]">
<input type="checkbox" value="Run" name="sports[]">


Is it possible to count items that are inside
sports[]
array?

Answer Source

check length of checked items using :checked selector in jquery and make it unchecked if 3 of them are selected

$('input[name="sports[]"]:checkbox').change(function() {
    if($('input[name="sports[]"]:checked').length>2)
    {
        alert("You can't select 3 items");
        this.checked=false;
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" value="Walk" name="sports[]">
<input type="checkbox" value="Swim" name="sports[]">
<input type="checkbox" value="Run"  name="sports[]">