<!DOCTYPE html>
<html lang="zh-TW">
<head>
<meta charset="UTF-8">
<title>動態表單欄位 Demo</title>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<style>
.form-row { display: flex; align-items: center; gap: 0.5rem; margin: 0.5rem 0; }
.form-row label { width: 80px; text-align: right; flex-shrink: 0; }
.form-row input[type=text] { flex: 1; padding: 0.4rem; font-size: 1rem; }
.btn { padding: 0.4rem 0.8rem; cursor: pointer; }
.btn-danger { background: #ff6b6b; color: white; border: none; }
</style>
</head>
<body>
<h2>投票選項設定 (最多 5 項)</h2>
<form id="voteForm">
<div id="optionsContainer">
<!-- 初始一組 -->
<div class="form-row option-row" data-index="1">
<label>選項 1</label>
<input type="text" name="options[]" class="option-input" placeholder="請輸入選項文字">
</div>
</div>
<div class="form-row">
<label></label>
<button type="button" id="btnAdd" class="btn">+ 新增選項</button>
<button type="button" id="btnReset" class="btn">重置內容</button>
<button type="submit" class="btn">儲存</button>
</div>
</form>
<script>
const MAX_OPTIONS = 5;
const $container = $('#optionsContainer');
const $addBtn = $('#btnAdd');
const $resetBtn = $('#btnReset');
// 新增選項
$addBtn.on('click', () => {
const currentCount = $container.children('.option-row').length;
if (currentCount >= MAX_OPTIONS) {
alert(`最多只能新增 ${MAX_OPTIONS} 個選項!`);
return;
}
const newIndex = currentCount + 1;
const $newRow = $(`
<div class="form-row option-row" data-index="${newIndex}">
<label>選項 ${newIndex}</label>
<input type="text" name="options[]" class="option-input" placeholder="請輸入選項文字">
<button type="button" class="btn btn-danger btn-del">刪除</button>
</div>
`);
$container.append($newRow);
$newRow.find('input').trigger('focus'); // 自動聚焦
});
// 刪除單一選項 (事件委派)
$container.on('click', '.btn-del', function() {
if ($container.children('.option-row').length <= 1) {
alert('至少保留一個選項');
return;
}
$(this).closest('.option-row').remove();
reindex(); // 重新編號
});
// 重置所有輸入內容
$resetBtn.on('click', () => {
$container.find('.option-input').val('').first().trigger('focus');
});
// 重新編號標籤與 data-index
function reindex() {
$container.children('.option-row').each(function(i) {
const idx = i + 1;
$(this).attr('data-index', idx).find('label').text('選項 ' + idx);
});
}
// 表單送出示範
$('#voteForm').on('submit', e => {
e.preventDefault();
const data = $(this).serializeArray();
console.log('提交資料:', data);
alert('查看 Console 見提交資料結構');
});
</script>
</body>
</html>
.on('click', '.btn-del', ...): 動態新增的刪除按鈕無需重新綁定,效能佳、記憶體無洩漏。name="options[]" 陣列命名: 後端 (PHP/Java/Node) 可直接接收陣列,無需手動拼裝。reindex(): 刪除後保持流水號連續,提升使用者體驗。SortableJS 對 #optionsContainer 啟用拖曳,拖曳結束後呼叫 reindex()。jquery-validation,規則:required、minlength、remote 檢查重複。input 事件防抖存入 localStorage,頁面重載自動還原。| 錯誤做法 | 後果 | 正確做法 |
|---|---|---|
直接 $('#btnDel').click(...) 綁定動態元素 | 新增的按鈕無效 | 事件委派 $container.on('click', '.btn-del', ...) |
用 clone() 複製第一組 | ID 重複、事件重複綁定 | 模板字串重新建構或 clone(true) 深度複製事件 |
| 刪除後不重新編號 | 流水號斷層、使用者困惑 | 統一 reindex() 函式 |
這個模式是後台管理系統「動態表單列表」的標準解法,掌握後可輕鬆應用於標籤管理、屬性配置、多圖上傳等場景。