Dealing with posting large number of checkboxes

David Carr

Javascript Tutorials HTML

When you have a form with lots of checkboxes, you may hit a limit to how many you can post. I had this issue with a form that had over 125 checkboxes I found once the limit was reached not all checkboxes could be posted.

My solution was using jQuery to scan all checkboxes read their values then stored as a comma separated list in a hidden input.

Let’s put this into practice below is a table of records wrapped inside a form, the top checkbox when checked all checkboxes underneath will be checked.

Each checkbox has a value. Now the jQuery code needed to toggle the checkboxes:

<form method="get">
<input type='hidden' name="ids" id="ids">
<table class='table table-striped table-hover table-bordered'>
    <thead>
        <tr>
            <th><input type="checkbox" id="selecctall" /></th>
            <th>First Name</th>
            <th>Last Name</th>
            <th>Email</th>
        </tr>
    </thead>
    
    <tbody>
        <?php
        foreach($contacts as $row) {
            echo "<tr>";
                echo "<td><input type='checkbox' value='$row->id' class='checkbox' /></td>";
                echo "<td>$row->firstName</td>";
                echo "<td>$row->lastName</td>";
                echo "<td>$row->email</td>";
            echo "</tr>";
        }
        ?>
    </tbody>
</table>

<p><p><button type="submit" class="btn btn-success" name="submit"><i class="fa fa-check"></i> <i class='fa fa-envelope'></i> Submit </button></p>
</form>

Each checkbox has a value. Now the jQuery code needed to toggle the checkboxes:

<script type="text/javascript">
$(document).ready(function () {

    //on click check each checkbox
    $('#selecctall').click(function (event) {
        if (this.checked) {
            //loop through each checkbox
            $('.checkbox').each(function () { 
                $(this).prop('checked', true); //check 
            });
        } else {
            //loop through each checkbox
            $('.checkbox').each(function () { 
                $(this).prop('checked', false); //uncheck              
            });
        }

        //collect each checkbox value
        var checkedRows = $('.checkbox:checked').map( function() {
            return this.value;
        }).get().join(",");

        //add the comma seperated list to the input 
        $('#ids').val(checkedRows);

    });

    //on checking a single checkbox update the comma seperated list
    $('.checkbox').change(function(){
        var checkedRows = $('.checkbox:checked').map( function() {
            return this.value;
        }).get().join(",");

        $('#ids').val(checkedRows);
    });

});
</script>

Read articles directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Copyright © 2006 - 2024 DC Blog - All rights reserved.