映射不带索引的复选框的动态数组


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复选框数组,但这个答案显然只适用于带有索引的数组。

这里最好的方法是什么?

编辑:

我还在服务器端检查表单是否有错误,如果有错误,我会将其重定向回,所以我需要能够根据提交的值"重建"表单。

我看到的一个技巧是在提交值为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);
    });
});