最小可行程式碼
<button onclick="addInput()">新增輸入框</button>
<div id="container"></div>
<script>
function addInput() {
var input = document.createElement('input');
input.type = 'text';
input.value = '預設值 ' + (document.querySelectorAll('#container input').length + 1);
document.getElementById('container').appendChild(input);
}
</script>
進階版:支援刪除、編號、驗證
<button id="addBtn">+ 新增欄位</button>
<div id="fields"></div>
<script>
document.getElementById('addBtn').addEventListener('click', function() {
var wrapper = document.createElement('div');
wrapper.className = 'field-row';
wrapper.style.marginBottom = '8px';
var index = document.querySelectorAll('#fields .field-row').length + 1;
wrapper.innerHTML =
'<input type="text" name="field[]" placeholder="欄位 ' + index + '" required> ' +
'<button type="button" class="remove-btn">刪除</button>';
// 刪除功能(事件委派更佳,這裡示範直接綁定)
wrapper.querySelector('.remove-btn').onclick = function() {
wrapper.remove();
reIndex();
};
document.getElementById('fields').appendChild(wrapper);
});
function reIndex() {
document.querySelectorAll('#fields .field-row').forEach(function(row, i) {
row.querySelector('input').placeholder = '欄位 ' + (i + 1);
});
}
</script>
表單提交時取得所有值
document.getElementById('myForm').addEventListener('submit', function(e) {
e.preventDefault();
var values = Array.from(document.querySelectorAll('input[name="field[]"]'))
.map(function(input) { return input.value.trim(); })
.filter(function(v) { return v !== ''; });
console.log('提交資料:', values);
// 傳送至後端...
});
最佳實踐提醒
- 使用
name="field[] 陣列命名,PHP/Node 等後端可直接解析為陣列。
- 動態新增元素後,事件委派(
parent.addEventListener('click', ...))優於逐個綁定。
- 大量欄位時考慮虛擬清單或分頁,避免 DOM 節點過多導致效能下降。
- 無障礙:新增
aria-label、id 關聯 label。