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?

2
  • 1
    Saving checkboxes with laravel and ajax answer from 2017. stackoverflow.com/q/47874383/3585500 Commented May 3, 2019 at 11:01
  • Formdata can accept an html form as parameter and automaticaly serialize the form fields into form data. Commented May 3, 2019 at 11:21

1 Answer 1

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.