Capturing checkboxes with an array.

Posted 6 months ago by finchy70

I have a form that contains a loop that displays a question and checkbox.

<form action="/vehicle_checks/{{$vehicle->id}}" method="POST" class="form-control">
            <label name="mileage" for="mileage">Please record the vehicle mileage.</label>
            <input type="number" name="mileage" class="form-control mb-2" required>

            @foreach($questions as $question)
                <div class="row">
                    <div class="col-8"><label for="answer[]" class="ml-2">{{$question->question}}</label></div>
                    <div class="col-4">
                        <div class="form_check form-check-inline">
                            <input class="mr-2" type="checkbox" name="answer[]" checked>Yes
            <label name="notes" for="notes"><strong>Record any notes if applicable.</strong></label>
            <textarea rows="5" class="form-control" name="notes"></textarea>
            <div class="row">
                <a href="/vehicle_checks/{{$vehicle->id}}" class="ml-auto btn btn-danger mt-3 mr-2">Cancel</a>
                <button type="submit" class="btn btn-success mt-3 mr-3">Save</button>

I an using answer[] to capture the status of the checkboxes but they only add to the array when set to "on" status. I need every value in the array with its on / off status so I can save the answer against the specific question. For example if someone saved the form without checking any checkbox, the answer array would contain 14 values of "off" (as that is currently the amount of questions), or if they just check question 3 then answer[2] would be set to "on";

Is there a way to do this?

Please sign in or create an account to participate in this conversation.