有時候我們需要一鍵清空整個表單的內容。下面這個 clearForm 函數會遍歷表單中的所有輸入元素,根據類型分別處理,達到徹底清空的效果。
value 設為空字符串。checked 狀態,但不改動它們的 value。selectedIndex 設為 -1,取消所有選中項。function clearForm(form) {
// 遍歷傳入表單中的所有輸入元素
$(':input', form).each(function () {
var type = this.type;
var tag = this.tagName.toLowerCase();
// 文本框、密碼框、文本區域可以直接清空 value
if (type == 'text' || type == 'password' || tag == 'textarea')
this.value = "";
// 複選框和單選框只需清除勾選狀態,不改變 value
else if (type == 'checkbox' || type == 'radio')
this.checked = false;
// 下拉框把 selectedIndex 設為 -1(單選、多選均適用)
else if (tag == 'select')
this.selectedIndex = -1;
});
};
只需調用 clearForm(form) 並傳入目標表單,即可快速重置表單中的所有數據。