![](/img/trans.png)
[英]How to add name attribute of input field dynamically using Javascript/Jquery
[英]How to Dynamically set the index of array in the name attribute of the input field using Javascript
如何使用javascript在輸入字段的名稱屬性中動態設置數組的索引?
<input type="text" name="item[][name]">
<input type="text" name="item[][description]">
<input type="text" name="item[][brand]">
如果我添加相同的輸入字段集或使用 javascript 復制它,結果應該如下所示:
<input type="text" name="item[0][name]">
<input type="text" name="item[0][description]">
<input type="text" name="item[0][brand]">
<input type="text" name="item[1][name]">
<input type="text" name="item[1][description]">
<input type="text" name="item[1][brand]">
可能你做錯了事。 如果您使用 js 創建此字段,則將索引放在那里。
使用普通 js 的示例。
var maxInputNum = 5;
var inputName = document.createElement('input'),
inputDescription = document.createElement('input'),
inputBrand = document.createElement('input');
maxInputNum++;
inputName.name = 'item[' + maxInputNum + '][name]';
inputDescription.name = 'item[' + maxInputNum + '][description]';
inputBrand.name = 'item[' + maxInputNum + '][brand]';
form.appendChild(inputName);
form.appendChild(inputDescription);
form.appendChild(inputBrand);
當然,您可以使用 jQuery 來簡化示例。
var maxInputNum = 5;
maxInputNum++;
var $inputName = $('<input type="text" name="item[' + maxInputNum + '][name]">'),
$inputDescription = $('<input type="text" name="item[' + maxInputNum + '][brand]">'),
$inputBrand = $('<input type="text" name="item[' + maxInputNum + '][description]">');
$('#form').append($inputName);
$('#form').append($inputDescription);
$('#form').append($inputBrand);
但更好的解決方案是使用 angularjs 之類的東西。
在這里,您可以根據所選 HTMLElements 數組中的順序更新容器“[digits]”的所有名稱屬性。 您可以創建一個名為 update order 的函數,並在每次發生某些事情並影響 order 時調用它... Sortable Elements 或 Delete Element 數組中的排序順序。
$("input").each(function (indexitem, itemdata) {
var name = $(itemdata).attr("name");
if (name !== undefined && name !== null) {
const regex = /\[[\d]+\]/gi;
var newname = name.replace(regex, `[${index}]`);
$(itemdata).attr("name", newname);
}
});
您可以簡單地刪除索引號而不是排序。 瀏覽器仍然會將值作為數組傳遞,同時保持順序。
let allIndexedElements=document.querySelectorAll('[name*="item["]');
for (const el of allIndexedElements) {
el.name = el.name.replace(/\[\d+\]/ig, '[]');
}
如果您想確保保留訂單,您可以增加索引號而不是刪除它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.