以下程式摘自 jquery.form.js,由於清空表單這個功能通用性極高,也很適合獨立拆出來使用,因此特別整理出來作為參考。整段程式碼言簡意賅,能清楚說明各類表單元素應如何被重置。
這個方法會對表單內的輸入欄位做以下處理:文字欄位的值設為空字串;select 的 selectedIndex 設為 -1;checkbox 與 radio 的 checked 設為 false;而 submit、button、reset、hidden 類型以及 button 元素則不受影響。
$.fn.clearForm = function(includeHidden) {
return this.each(function() {
$('input,select,textarea', this).clearFields(includeHidden); // this 表示限定上下文,多表單時只作用於被呼叫者
});
};
$.fn.clearFields = $.fn.clearInputs = function(includeHidden) {
var re = /^(?:color|date|datetime|email|month|number|password|range|search|tel|text|time|url|week)$/i;
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)) {
$(this).replaceWith($(this).clone(true));
} else {
$(this).val('');
}
}
else if (includeHidden) {
// includeHidden 可為 true,或為一個選擇器字串
if ( (includeHidden === true && /hidden/.test(t)) ||
(typeof includeHidden == 'string' && $(this).is(includeHidden)) ) {
this.value = '';
}
}
});
};
值得注意的是 file 型別的處理:在舊版 IE 下無法直接清空,於是透過 clone 節點再替換的方式繞過;而 includeHidden 參數除了可傳 true,也能傳入選擇器字串,達到只清除特定 hidden 欄位的細緻控制。