0

I have a bunch of checkboxes in my laravel-app, which I want to save as an array in my MySQL database but I'm not sure how to do it.

So here are my input fields:

<input type="checkbox" class="form-check-input" name="vehicle[]" value="bmw">BMW
<input type="checkbox" class="form-check-input" name="vehicle[]" value="audi">Audi
<input type="checkbox" class="form-check-input" name="vehicle[]" value="mercedes">Mercedes
<input type="checkbox" class="form-check-input" name="vehicle[]" value="chrysler">Chrysler
<input type="checkbox" class="form-check-input" name="vehicle[]" value="chevrolet">Chevrolet
<input type="checkbox" class="form-check-input" name="vehicle[]" value="ford">Ford

For simple input fields I do this in my .js file:

var formData = new FormData();
    formData.append(
        "name",
        $("#uploadModal")
            .find('input[name="name"]')
            .val()
    );
// etc. etc,

and then later on I submit the data by using axios:

 axios.post($("#uploadModal form").attr("action"), formData) ...

How can I add the checked checkbox array to the formData?

AmirBll
  • 1,081
  • 1
  • 13
  • 25
ST80
  • 3,565
  • 16
  • 64
  • 124
  • 1
    Saving checkboxes with laravel and ajax answer from 2017. https://stackoverflow.com/q/47874383/3585500 – ourmandave May 03 '19 at 11:01
  • [Formdata](https://developer.mozilla.org/en-US/docs/Web/API/FormData/FormData) can accept an html form as parameter and automaticaly serialize the form fields into form data. – Nikos M. May 03 '19 at 11:21

1 Answers1

1
<input type="checkbox" class="form-check-input" name="vehicle[]" value="bmw">BMW
<input type="checkbox" class="form-check-input" name="vehicle[]" value="audi">Audi
<input type="checkbox" class="form-check-input" name="vehicle[]" value="mercedes">Mercedes
<input type="checkbox" class="form-check-input" name="vehicle[]" value="chrysler">Chrysler
<input type="checkbox" class="form-check-input" name="vehicle[]" value="chevrolet">Chevrolet
<input type="checkbox" class="form-check-input" name="vehicle[]" value="ford">Ford

<script>
function sendCall(){
    var formData = new FormData();
    var vehicleList = [];
    $("[name='vehicle[]']").each(function(){
       if($(this).is(":checked")){
           vehicleList.push($(this).val());
       }
    });

    formData.append("vehicle",vehicleList);

---> add axios request with formData object
}

--> call sendCall on click btn
</script>

sarvon ks
  • 626
  • 3
  • 10