【问题标题】:How to save checkbox array in MySQL database by using Javascript如何使用 Javascript 在 MySQL 数据库中保存复选框数组
【发布时间】:2019-09-21 22:03:00
【问题描述】:

我的laravel-app 中有一堆复选框,我想将它们作为数组保存在我的MySQL 数据库中,但我不知道该怎么做。

这是我的输入字段:

<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

对于简单的输入字段,我在 .js 文件中执行此操作:

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

然后我使用axios提交数据:

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

如何将选中的checkbox 数组添加到formData?

【问题讨论】:

标签: javascript mysql laravel axios


【解决方案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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-29
    • 2015-12-12
    • 2016-02-02
    • 1970-01-01
    相关资源
    最近更新 更多