jquery.form.js 是經典的表單 Ajax 化插件,其內建的 clearForm() / clearFields() 方法提供了極為完善的表單重置功能。本文深度解析其核心源碼並展示實戰用法。
$.fn.clearForm = function(includeHidden) {
return this.each(function() {
// this 為 form 元素,建立上下文確保多表單隔離
$('input,select,textarea', this).clearFields(includeHidden);
});
};
$.fn.clearFields = $.fn.clearInputs = function(includeHidden) {
// 正則匹配所有文字類型 input(排除 hidden)
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();
// 文字類 input / textarea -> 清空 value
if (re.test(t) || tag === 'textarea') {
this.value = '';
}
// checkbox / radio -> 取消選中
else if (t === 'checkbox' || t === 'radio') {
this.checked = false;
}
// select -> 重置 selectedIndex
else if (tag === 'select') {
this.selectedIndex = -1;
}
// file 輸入框特殊處理
else if (t === 'file') {
if (/MSIE/.test(navigator.userAgent)) {
// IE: 替換節點以清除文件路徑
$(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 = '';
}
}
// submit/button/reset/hidden/button 元素默認不處理
});
};
$(selector, this) 確保多表單頁面互不干擾.val('')includeHidden 支援布林值與選擇器雙模式this 支援 jQuery 鏈式風格// 清空整個表單(不含隱藏欄位)
$('#myForm').clearForm();
// 清空包含隱藏欄位
$('#myForm').clearForm(true);
// 僅清空帶有 .special 類的隱藏欄位
$('#myForm').clearForm('.special:hidden');
$('#myForm').ajaxForm({
beforeSubmit: function() {
// 提交前驗證
return validateForm();
},
success: function(response) {
if (response.success) {
// 成功後清空表單並提示
$('#myForm').clearForm();
showToast('提交成功');
} else {
showError(response.msg);
}
}
});
// 清空某區域內所有輸入控件
$('.search-panel').find('input,select,textarea').clearFields();
// 重置特定字段組
$('#filter-form :input').not('[name="csrf_token"]').clearFields();
| 誤區 | 正確認知 |
|---|---|
| 以為 clearForm 會觸發 change 事件 | 直接修改 DOM 屬性不會觸發事件,如需觸發請手動 .trigger('change') |
| 隱藏欄位未清空以為是 bug | 默認不清空 hidden,需顯式傳 true 或選擇器 |
| File 輸入在 IE 下無法清空 | 源碼已處理 IE 克隆替換方案,需確保 jQuery 版本支援 |
| 按鈕類 input 被誤清空 | 源碼明確排除 submit/button/reset/hidden/button 類型 |
若不依賴 jquery.form.js,可使用原生 JS 實現輕量版:
function clearForm(formEl, includeHidden = false) {
const inputs = formEl.querySelectorAll('input, select, textarea');
inputs.forEach(el => {
const t = el.type, tag = el.tagName.toLowerCase();
if (['color','date','datetime-local','email','month','number','password','range','search','tel','text','time','url','week'].includes(t) || tag === 'textarea') {
el.value = '';
} else if (t === 'checkbox' || t === 'radio') {
el.checked = false;
} else if (tag === 'select') {
el.selectedIndex = -1;
} else if (t === 'file') {
el.value = ''; // 現代瀏覽器支援
} else if (includeHidden && (t === 'hidden' || (typeof includeHidden === 'string' && el.matches(includeHidden)))) {
el.value = '';
}
});
}
// 使用
clearForm(document.getElementById('myForm'), true);
jquery.form.js 的清空邏輯展示了成熟庫對邊界情況的周全考量。理解其源碼不僅能正確使用,更能在需要時提取核心邏輯構建零依賴工具函數。