2015-02-05 25 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