[英]How to increment an input name by cloning?
我有一個帶有一些輸入 type=text 的 html 表單。 我可以克隆每個輸入,但我想恢復名稱以在我的數據庫中插入信息。 因此,我必須增加所有名稱。 我只能增加一種類型的輸入而不是多種類型。
<body>
<button id="clone">Cloner</button>
<button id="removebutton">Remove</button>
<form id="myForm">
<div class="equipment" id="eqp">
<h4 class="title4">EQUIPEMENT 1 / EQUIPMENT 1</h4>
<label>Date de prêt / Loan date:</label>
<input type="text" name="loandate" id="datepicker" placeholder="ex: 20170101"/><br/><br/>
<label>Nom du produit / Product Name:</label>
<input type="text" name="productname" placeholder="ex: Asus"/><br/><br/>
<label>Type:</label>
<input type="text" name="type"/><br/><br/>
<label>Numéro de série / Serial Number:</label>
<input type="text" name="serialnumber" placeholder="ex: A003565DS65"/><br/><br/>
<label>Statuts / Status:</label>
<select name="status">
<option>gg</option>
<option>hh</option>
</select><br/><br/>
</div>
</form>
</body>
</html>
JS:
$('#clone').click(function () {
$('#myForm').append($('#eqp:last').clone());
$('#myForm div').each(function (i) {
var textinput1 = $(this).find('input');
var textinput2 = $(this).find('input[text="productname"]');
var select = $(this).find('select');
i++;
textinput1.eq(0).attr('name', 'loandate' + i);
select.eq(0).attr('name', 'status' + i);
});
});
$("#removebutton").click(function() {
if ($('.equipment').length > 1)
$('.equipment:last').remove()
});
//});
謝謝你的幫助 !
使用<input name="loandate[]" >
您不需要增加名稱,您將獲得數組的結果
以下是您需要更改為 HTML 和 JS 的內容:
$('#clone').click(function () { $('#myForm').append($('.equipment:last').clone()); $('#myForm div').each(function (i) { }); }); $("#removebutton").click(function() { if ($('.equipment').length > 1) $('.equipment:last').remove() });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button id="clone">Cloner</button> <button id="removebutton">Remove</button> <form id="myForm"> <div class="equipment"> <h4 class="title4">EQUIPEMENT 1 / EQUIPMENT 1</h4> <label>Date de prêt / Loan date:</label> <input type="text" name="loandate[]" id="datepicker" placeholder="ex: 20170101"/><br/><br/> <label>Nom du produit / Product Name:</label> <input type="text" name="productname[]" placeholder="ex: Asus"/><br/><br/> <label>Type:</label> <input type="text" name="type[]"/><br/><br/> <label>Numéro de série / Serial Number:</label> <input type="text" name="serialnumber[]" placeholder="ex: A003565DS65"/><br/><br/> <label>Statuts / Status:</label> <select name="status[]"> <option>gg</option> <option>hh</option> </select><br/><br/> </div> </form>
考慮到您的 html 有錯誤。 設備 div 元素有一個 ID ( #eqp
)。 克隆該 div 后,您將獲得多個具有相同 ID 的元素。 (這不好)。
你需要改變的是:
name[]
PHP 示例:
$i = 0;
do{
$loandate = $_POST['loandate'][$i];
$type = $_POST['type'][$i]
//...
$i++;
}while(isset($_POST['loandate'][$i]))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.