DIV CSS 佈局教程網

jquery.form.js 的 clearForm 實作解析與表單重置技巧
編輯:JavaScript綜合知識     

以下程式碼摘錄自 jquery.form.js。這個方法實用性很強,也能獨立拆出來使用,程式碼言簡意賅,很適合作為學習參考。

clearForm:清空整個表單

/**
 * Clears the form data. Takes the following actions on the form's input fields:
 * - input text fields will have their 'value' property set to the empty string
 * - select elements will have their 'selectedIndex' property set to -1
 * - checkbox and radio inputs will have their 'checked' property set to false
 * - inputs of type submit, button, reset, and hidden will *not* be effected
 * - button elements will *not* be effected
 */
$.fn.clearForm = function(includeHidden) {
    return this.each(function() {
        // this 表示設定上下文環境,有多個表單時只作用於呼叫的表單
        $('input,select,textarea', this).clearFields(includeHidden);
    });
};

註解中說明了各類欄位的處理方式:文字輸入清空值、下拉選單把 selectedIndex 設為 -1、核取方塊與單選鈕取消勾選,而 submit/button/reset/hidden 則不動。最後這點很重要——清空表單不該把使用者精心設定好的隱藏欄位也清掉。

clearFields:逐欄位處理的實際邏輯

$.fn.clearFields = $.fn.clearInputs = function(includeHidden) {

    // 這些 type 需要清空 value
    var re = /^(?:color|date|datetime|email|month|number|password|range|
                search|tel|text|time|url|week)$/i;
    // 注意 'hidden' 不在這個清單裡

    return this.each(function() {
        var t = this.type,
            tag = this.tagName.toLowerCase();

        if (re.test(t) || tag == 'textarea') {
            this.value = '';
        }

        else if (t == 'checkbox' || t == 'radio') {
            this.checked = false;
        }

        else if (tag == 'select') {
            this.selectedIndex = -1;
        }

        else if (t == "file") {
            if (/MSIE/.test(navigator.userAgent)) {
                // 舊 IE 不允許直接改 file 的值,只能重建節點
                $(this).replaceWith($(this).clone(true));
            } else {
                $(this).val('');
            }
        }

        else if (includeHidden) {
            // includeHidden 可以傳 true,也可以傳一個選擇器字串
            // 例如:$('#myForm').clearForm('.special:hidden')
            // 上面這行會清空 class 為 special 的隱藏欄位
            if ((includeHidden === true && /hidden/.test(t)) ||
                (typeof includeHidden == 'string' && $(this).is(includeHidden))) {
                this.value = '';
            }
        }
    });
};

幾個值得學習的設計細節

1. 用正則一次比對所有文字類型

HTML5 新增了大量 input type(color、date、email、number、range、tel、url、week 等),它們的共同點是需要清空 value。用一個正則一次處理,比寫一长串 || 判斷優雅得多。

2. 上下文設定避免誤清其他表單

$('input,select,textarea', this) 的第二個參數是查找上下文,限定只在當前表單內搜尋。頁面上有多個表單時,這個寫法能精準作用於目標表單。

3. file 欄位的特殊處理

基於安全考量,瀏覽器不允許程式直接設定 file 輸入的值,甚至連清空都曾經被禁止。舊版 IE 完全無法清空,只能用 clone(true) 複製一個新節點替換掉原來的——這也是為什麼 clone 要傳 true,為了保留原本綁定的事件。

4. includeHidden 的雙重語意

這個參數設計得很巧:傳 true 表示清空所有 hidden 欄位;傳字串則當作選擇器,只清空符合條件的部分。一個參數同時支援兩種粒度,呼叫端很靈活。

clearForm 與 form.reset() 的差別

很多人會問:原生不是有 <form>.reset() 嗎?兩者語意完全不同:

  • reset() 把表單還原到初始狀態——也就是頁面載入時 HTML 中 value 屬性所寫的值。如果 <input value="abc">,reset 之後會回到 "abc"。
  • clearForm() 把表單清成空白——所有值都變成空字串、所有勾選都取消。

所以「重新填寫」用 clearForm,「取消編輯還原原值」用 reset。

現代化的簡化寫法

如果不需要那麼細緻的分類處理,清空表單其實可以很簡短:

function clearForm(form) {
    form.querySelectorAll('input, select, textarea').forEach(function(el) {
        var type = el.type;

        if (type === 'checkbox' || type === 'radio') {
            el.checked = false;
        } else if (el.tagName === 'SELECT') {
            el.selectedIndex = -1;
        } else if (type === 'file') {
            el.value = '';        // 現代瀏覽器都允許清空了
        } else if (type !== 'submit' && type !== 'button'
                && type !== 'reset' && type !== 'hidden') {
            el.value = '';
        }
    });
}

幾點說明:

  • 舊 IE 的 file 欄位 hack 已經不需要了,現代瀏覽器一律允許 el.value = ''。
  • UA 嗅探(/MSIE/.test(navigator.userAgent))不應再用,這是公認的反模式。
  • 若只是想恢復預設值,直接呼叫 form.reset() 即可,不必自己寫。
  • React、Vue 這類框架中,表單狀態由框架管理,直接操作 DOM 的值會與框架內部狀態不同步。這種情況應透過框架的狀態設定介面處理。

這段程式碼的核心價值在於那個正則清單與 select 的 selectedIndex = -1 技巧——後者是把下拉選單設為「無任何選項被選中」的唯一標準方法,很多人會誤用 selectedIndex = 0(那其實是選第一項)。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved