「重填」或「取消」功能常需要一次清空整份表單。由於不同類型的表單元件清空方式各異,本文提供一個能處理各種元件的通用函數。
這個函數會遍歷表單內所有輸入元件,依類型分別處理:文字框與密碼框直接清空 value,核取方塊與單選鈕改設 checked 為 false,下拉選單則把 selectedIndex 設為 -1。
function clearForm(form) {
$(':input', form).each(function() {
var type = this.type;
var tag = this.tagName.toLowerCase();
if (type == 'text' || type == 'password' || tag == 'textarea')
this.value = "";
else if (type == 'checkbox' || type == 'radio')
this.checked = false;
else if (tag == 'select')
this.selectedIndex = -1;
});
};
把表單傳入 clearForm(form) 即可一次清空所有欄位,省去逐一重設的麻煩。