jeudi 5 mars 2020

Convert checkbox state to boolean value

So for a register form in a Laravel application I need a student to check a checkbox if they are an outgoing student. In the RegisterController.php the is_outgoing value is validated to be a boolean.

I am having difficulties returning the is_outgoing value with the form as a boolean true of false (based on if it is checked or not)

My best attempt is shown below, but the RegisterController doesn't seem te recieve any value for is_outgoing as the register form always trows "is outgoing field is required".

I tried renaming the actual checkbox under a different name, and adding a hidden input using the is_outgoing name using JQuery based on the checkbox state.

HTML:

<form id="#form" method="POST" action="" onsubmit="checkboxToBoolean()">
<div class="form-group row">
                            <label for="is_outgoing_checkbox" class="col-md-4 col-form-label text-md-right"></label>
                            <div class="col-md-6">
                                <input id="is_outgoing_checkbox" type="checkbox" class="form-control @error('is_outgoing') is-invalid @enderror" name="is_outgoing_checkbox">
                                @error('is_outgoing')
                                <span class="invalid-feedback" role="alert">
                                                    <strong></strong>
                                                </span>
                                @enderror
                            </div>
                        </div>

Script at bottom of HTML:

<script>
        function checkboxToBoolean() {
            let is_outgoing = $("#is_outgoing_checkbox").is(":checked");
            $("<input />").attr("type", "hidden")
                .attr("name", "is_outgoing")
                .attr("value", is_outgoing)
                .appendTo("#form");
        }
</script>

Thanks.




Aucun commentaire:

Enregistrer un commentaire