Limit number of checkbox selections using javascript

This tutorial shows how to limit the number of checkbox selections in a group of checkboxes. Suppose you have a group fo checkboxes in a form or in a div or table cell or wherever else and you need a requirement that a user can select maximum of two or three or n number of checkboxes then you need to restrict it using javascript or jquery. The below example shows how to achieve it.

Using form example. The below example shows that maximum of two checkboxes can be selected.
HTML

<body>
    <form method="post" name="form_name" id="form_name">
        <input type="checkbox" name="check[]" value="CheckBox 1"/>
        <input type="checkbox" name="check[]" value="CheckBox 2"/>
        <input type="checkbox" name="check[]" value="CheckBox 3"/>
    </form>
    <script type="text/javascript">checkBoxLimit()</script>
</body>

 

JavaScript

<script type="text/javascript">
function checkBoxLimit() {
    var checkBoxGroup = document.forms.form_name.check;
    var limit = 2;
    for (var i = 0; i < checkBoxGroup.length; i++) {
        checkBoxGroup[i].onclick = function() {
            var checkedcount = 0;
            for (var i = 0; i < checkBoxGroup.length; i++) {
                checkedcount += (checkBoxGroup[i].checked) ? 1 : 0;
            }
            if (checkedcount > limit) {
                alert("You can select only a maximum of " + limit + " checkboxes.");
                this.checked = false;
            }
        }
    }
}
</script>

 

Using div example. You can place checkboxes in any tag using attribute id. The below example shows that only one checkbox can be selected.

HTML

<div id="checkboxgroup">
<input type="checkbox" value="CheckBox 1" name="check[]">
<input type="checkbox" value="CheckBox 2" name="check[]">
<input type="checkbox" value="CheckBox 3" name="check[]">
</div>
<script type="text/javascript">
    onlyOneCheckBox()
</script>

 

JavaScript

<script type="text/javascript">
function onlyOneCheckBox() {
    var checkboxgroup = document.getElementById('checkboxgroup').getElementsByTagName("input");
    var limit = 1;
    for (var i = 0; i < checkboxgroup.length; i++) {
        checkboxgroup[i].onclick = function() {
            var checkedcount = 0;
                for (var i = 0; i < checkboxgroup.length; i++) {
                checkedcount += (checkboxgroup[i].checked) ? 1 : 0;
            }
            if (checkedcount > limit) {
                alert("You can only select a maximum of " + limit + " checkbox.");
                this.checked = false;
            }
        }
    }
}
</script>

 

Thanks for your reading. Please leave a comment if you have any query.

Soumitra Roy Sarkar

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on JEE Tutorials Twitter Facebook  Google Plus Linkedin

Leave a Reply

Your email address will not be published. Required fields are marked *