【问题标题】:Store data from multiple inputs php存储来自多个输入 php 的数据
【发布时间】:2016-09-19 08:23:56
【问题描述】:

我有一个动态表单,用户可以在其中选择输入的数量。我不知道表单可以有多少输入,我想将结果存储在一个数组中。 这是我的 HTML:

<select name="number-children" id="number-children">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
</select>

我的 jQuery :

$("#number-children").change(function () {
    var str = "";
    var count = Number($("#number-children option:selected").val());
    for (var i = 0; i < count; i++) {
      str += '<label class="col-sm-2 control-label" for="child-'+i+'">Child ' + i
              + '</label> <div class="col-sm-10"><input type="text" name="child-'+i+'" class="form-control" id="child-'+i+'"></input></div>';
   }
   $("#children").html(str);
});

如何将每个输入的值添加到数组中以在 post php 请求中收集它?

谢谢!

【问题讨论】:

    标签: php jquery


    【解决方案1】:

    只是改变

    <input type="text" name="child-'+i+'" class="form-control" id="child-'+i+'"></input>
    

    <input type="text" name="child['+i+']" class="form-control" id="child-'+i+'"></input>
    

    【讨论】:

    • 要追加Abdus的答案,然后可以使用$_POST['child']作为数组,包含i的值作为键,输入字段值作为值;
    • 感谢您的帮助,它解决了我的问题!也感谢@jeroen!
    【解决方案2】:

    改变:

     $("#children").html(str);
    

    收件人:

    $("#children").append(str);
    

    【讨论】:

    • 谢谢,我现在可以发送动态数据了!
    【解决方案3】:

    将所有子元素放入 1 个数组中的最简单方法是在 html 中使用数组:

    str += '<label class="col-sm-2 control-label" for="child-'+i+'">Child ' + i
              + '</label> <div class="col-sm-10"><input type="text" name="child[]" class="form-control" id="child-'+i+'"></input></div>';
                                                                               ^^ here
    

    现在,当您发送表单时,您会将所有值作为数组保存在 $_POST['child'] 中,因此您可以轻松地循环遍历它们,而不管数字是多少。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-14
      • 2012-04-28
      相关资源
      最近更新 更多