映射没有索引的动态复选框数组

Map dynamic array of checkboxes without index

这个问题进一步建立在此处提出的问题的基础上: .

我有一组动态行,每行都有自己的输入字段。这些行可以动态添加到 DOM,所以我必须使用没有索引的输入数组(例如 fieldname[] 而不是 fieldname[1] 等)。

当我在这些行中使用复选框时出现问题。由于未选中时不会提交复选框,因此我无法知道哪个提交的复选框属于哪些行值。

我的表单示例:

<form>
<div class="row">
     <input type="text" name="product[]">
     <input type="text" name="qty[]"> 
     <input type="checkbox" name="projectline[]"> 
</div>
<div class="row">
    <input type="text" name="product[]">
    <input type="text" name="qty[]">
    <input type="checkbox" name="projectline[]"> 
</div>
<div class="row">
     <input type="text" name="product[]">
     <input type="text" name="qty[]">
     <input type="checkbox" name="projectline[]"> 
</div>
</form>

我在这里找到了类似问题的答案:php array of checkboxes,但答案显然只适用于具有索引的数组。

这里最好的方法是什么?

编辑:

我还在服务器端检查表单是否有错误,如果有问题则将其重定向回来,所以我需要能够 'reconstruct' 基于提交的值的表单。

我见过用于此的一个技巧是在每个提交值为 0 的相同字段的复选框之前放置一个隐藏字段。这样,如果您选中该复选框,它将覆盖 0 值复选框值,但如果您不这样做,您将得到 0 表示未选中,而不是数据中没有任何内容。

保留 运行 总索引的评论中的答案也可以工作,但会更复杂一些,具体取决于 DOM 可以修改的方式和时间。

我最终为每一行分配了一个索引号,每次添加一行时都会生成一个新的随机 ID。我使用 jQuery 作为克隆函数和事件绑定。

下面是我的完整解决方案。

这是我原来的表格:

<form>
<div class="row">
 <input type="text" name="product[0]">
 <input type="text" name="qty[0]"> 
 <input type="checkbox" name="projectline[0]"> 
</div>
</form>

我有一个模板行,我用它来克隆:

<div id="templaterow">
 <input type="text" name="product[%%index%%]">
 <input type="text" name="qty[%%index%%]">
 <input type="checkbox" name="projectline[%%index%%]"> 
</div>

复制行的按钮:

<button id="addrow" value="add new row"/>

以及绑定到按钮的函数:

$('#addrow').on('click',function()
{
    //template row is cloned and given the right attributes:
    var clone = $('#templaterow').clone(true, true);
    $('.row').last().after(clone);
    clone.addClass('row').removeAttr('id');

    // the %%index%% placeholder is replaced by a random index number between 100 and 9999999
    clone.html(function (index, html) {
        var rndIndex = Math.floor((Math.random() * 9999999) + 100);
        return html.replace(new RegExp('%%index%%','g'),rndIndex);
    });
});