2016-10-17 96 views
0

我有一個按鈕,它們用自己的id(i ++和r ++從原始)複製兩個輸入。當我提交表單並運行時:輸入重複的提交表格

foreach ($_POST as $id => $value) { 
    echo $value;    
} 

process.php頁面無法識別新輸入$ id或$ value。

的重複代碼如下:

document.getElementById('button').onclick = duplicate 
var i = 0; 
var r = 0; 
var items = document.getElementById('items'); 
var cantidad = document.getElementById('cantidad'); 
function duplicate() { 
var cloneitems = items.cloneNode(false); // "deep" clone 
cloneitems.id = "items" + ++r; // there can only be one element with an ID 
items.parentNode.appendChild(cloneitems); 
var cloneCantidad = cantidad.cloneNode(false); // "deep" clone 
cloneCantidad.id = "cantidad" + ++i; // there can only be one element with an ID 
cantidad.parentNode.appendChild(cloneCantidad); 
} 

我的HTML:

<form method="post" action="process.php" enctype="multipart/form-data"> 
<h4 class="input-margin">Items<button type="button" id="button" onclick="duplicate()" class="btn btn-primary margin-left input-margin">+</button></h4> 
    <div> 
    <div class="input-margin"> 
    <div class="col-xs-12 col-sm-6"> 
    // First duplicated input 
    <select class="input-margin form-control" id="items" placeholder="Nombre" name="item" data-style="btn-primary"> 
     <option></option> 
     <?php while($row = mysqli_fetch_array($itemResults)) : ?> 
     <option><?php echo $row['item']; ?></option> 
     <?php endwhile; ?> 
    </select> 
    </div> 
    <div class="col-xs-12 col-sm-6"> 
    // Second duplicated input 
    <input type="number" class="input-margin form-control txtboxToFilter" id="cantidad" placeholder="Cantidad" name="cantidad" min="1"> 
    </div> 
    </div> 
    </div> 
</div> 
<div class="col-xs-12 col-sm-12 submit-button"> 
    <button type="submit" class="btn btn-primary btn-block" name="submit" value="ingreso">Ingresar</button> 
</div> 
</form> 

用戶必須有,因爲他們想用盡可能多的重複的可能性。他們每個人都會有不同的輸入,這就是爲什麼我需要唯一的ID來改變MySQL。

爲什麼新的ID沒有被顯示或識別,並且有沒有更好的方法從重複的輸入中獲取所有的值?

+0

由於您沒有顯示您正在擺弄的HTML,所以我們無法提供幫助。 PHP並不關心JS代碼是什麼 - 它只會在提交表單時看到瀏覽器將HTML變成什麼。 –

+0

我會建議先使用jquery,它的方式更容易。使用jquery,我會使用serializeArrays函數來獲取表單的值,然後使用AJAX請求將其發送到您的服務器。 – Nicolas

回答

1

表單字段的名稱,而不是他們的ID。所以每個附加的輸入都會覆蓋其他輸入。區分名稱,你會得到每一個。或者你可以給這些輸入一個數組作爲名字: name="cantitad[]" 你將得到一個包含所有值的數組。

+0

工作就像一個魅力!謝謝你的幫助!在給出數組作爲名稱之後,我如何在PHP中使用這些值? –

+0

只是在每個陣列上使用一個foreach。如果您有多個陣列,您還可以在檢查密鑰的同步中使用它們 –