How to validate at least one checkbox is checked in a loop in Laravel form?

Tags: , , ,



I have a collection of checkboxes in my application. What I want to do is validate whether at least one is checked and enable a submit button. Basically a front end validation. According to the current code, the user must select all the checkboxes. I know this should be a small issue but as I am new to Laravel framework it’s a little bit confusing for me to understand. Please, someone, help me here.

@foreach ($roles as $role)
    <li>
        {{ Form::checkbox('roles[]', $role->id, null, ['class="role-li"', 'required']) }}
        {{ Form::label($role->name, ucfirst($role->name)) }}
    </li>
@endforeach

Answer

<form id="testform" action="/comment" method="post" class="m-0 mt-4">
    @for($i=0;$i<5;$i++)
        <input type="checkbox" name="vehicle1" value="Bike" class="role-li role{{$i}}" onclick='checktest()'> I have a bike<br>
    @endfor
</form>

<script>
        var minimumonechecked;
        var noofboxes = $('.role-li').length;
        function checktest(xyz) {
            minimumonechecked = false;
            for(i=0;i<noofboxes;i++){
                if ($('.role' + i).is(':checked')) {
                    minimumonechecked = true;
                }
            }
            console.log(minimumonechecked)
        };
</script>

this code works for me 🙂



Source: stackoverflow