萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery 動態新增/刪除/重置輸入欄位:限制數量、委派事件完整實作

功能需求

  • 動態新增文字輸入框,最多 5 組。
  • 每組包含流水號、輸入框。
  • 「重置選項」清空所有輸入框內容(不移除欄位)。
  • 新增欄位自動聚焦、預設提示文字。

完整實作 (jQuery 3.x + 委派事件)

<!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>

關鍵技術點

  1. 事件委派 .on('click', '.btn-del', ...): 動態新增的刪除按鈕無需重新綁定,效能佳、記憶體無洩漏。
  2. 模板字串建構 HTML: ES6 反引號可讀性高,避免字串拼接錯誤。
  3. name="options[]" 陣列命名: 後端 (PHP/Java/Node) 可直接接收陣列,無需手動拼裝。
  4. 重新編號 reindex(): 刪除後保持流水號連續,提升使用者體驗。
  5. 最小數量保護: 至少保留一組,避免表單空白提交。

進階擴充

  • 拖曳排序: 引入 SortableJS 對 #optionsContainer 啟用拖曳,拖曳結束後呼叫 reindex()。
  • 驗證規則: 整合 jquery-validation,規則:required、minlength、remote 檢查重複。
  • 本地儲存草稿: input 事件防抖存入 localStorage,頁面重載自動還原。
  • 巢狀欄位: 每選項再動態新增子屬性(如圖片、說明),遞套用相同模式。

常見坑點避雷

錯誤做法後果正確做法
直接 $('#btnDel').click(...) 綁定動態元素新增的按鈕無效事件委派 $container.on('click', '.btn-del', ...)
用 clone() 複製第一組ID 重複、事件重複綁定模板字串重新建構或 clone(true) 深度複製事件
刪除後不重新編號流水號斷層、使用者困惑統一 reindex() 函式

這個模式是後台管理系統「動態表單列表」的標準解法,掌握後可輕鬆應用於標籤管理、屬性配置、多圖上傳等場景。

copyright © 萬盛學電腦網 all rights reserved