2015-02-05 102 views
1

这个问题进一步建立在这里问的问题:How to map dynamic array of input fields映射无索引的复选框动态数组

我有一组动态的行,每个行都有自己的输入字段。这些行可以动态添加到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,但答案显然只适用于与指数阵列。

这里最好的办法是什么?

编辑:

我还检查错误服务器端的形式,并将其重定向回来,如果它是错误的,所以我需要能够“重建”基础上,提交的数据形式。

+2

是否有可能保持你有多少运行计数,并为它们分配索引,因为它们被放入? – 2015-02-05 13:33:35

+0

我同意QPaysTaxes。这似乎是最有意义的。 – vanamerongen 2015-02-05 13:33:59

+0

我可以通过JavaScript工作,但希望有一个更优雅的解决方案。 – nexana 2015-02-05 13:38:38

回答

0

我最终为每个行分配了一个索引号,每次添加一行时都会生成一个新的随机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> 

A键复制该行:

<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); 
    }); 
}); 
0

我见过的一个技巧是在每个提交相同字段的值为0的复选框之前放置一个隐藏字段。这样,如果选中复选框,它将用复选框覆盖0值值,但如果你不这样做,你会得到一个0而不是任何数据。

保留索引总数的注释的答案也可以起作用,但取决于如何以及何时可以修改DOM,有点复杂。

+0

我来过这个解决方案,但它wouldn在这种情况下工作,因为我使用非索引数组。当复选框被选中时,这两个字段都会被提交。 – nexana 2015-02-05 14:03:08