以下程式碼摘錄自 jquery.form.js。這個方法實用性很強,也能獨立拆出來使用,程式碼言簡意賅,很適合作為學習參考。
/**
* 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 則不動。最後這點很重要——清空表單不該把使用者精心設定好的隱藏欄位也清掉。
$.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 = '';
}
}
});
};
HTML5 新增了大量 input type(color、date、email、number、range、tel、url、week 等),它們的共同點是需要清空 value。用一個正則一次處理,比寫一长串 || 判斷優雅得多。
$('input,select,textarea', this) 的第二個參數是查找上下文,限定只在當前表單內搜尋。頁面上有多個表單時,這個寫法能精準作用於目標表單。
基於安全考量,瀏覽器不允許程式直接設定 file 輸入的值,甚至連清空都曾經被禁止。舊版 IE 完全無法清空,只能用 clone(true) 複製一個新節點替換掉原來的——這也是為什麼 clone 要傳 true,為了保留原本綁定的事件。
這個參數設計得很巧:傳 true 表示清空所有 hidden 欄位;傳字串則當作選擇器,只清空符合條件的部分。一個參數同時支援兩種粒度,呼叫端很靈活。
很多人會問:原生不是有 <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 = '';
}
});
}
幾點說明:
el.value = ''。/MSIE/.test(navigator.userAgent))不應再用,這是公認的反模式。form.reset() 即可,不必自己寫。這段程式碼的核心價值在於那個正則清單與 select 的 selectedIndex = -1 技巧——後者是把下拉選單設為「無任何選項被選中」的唯一標準方法,很多人會誤用 selectedIndex = 0(那其實是選第一項)。