有的時候,需要檢查使用者是否修改了一個表單中的內容,則可以使用下面的技巧,其中如果修改了表單的內容則傳回true,沒修改表單的內容則傳回false。程式碼如下:
function formIsDirty(form) { for (var i = 0; i var element = form.elements[i];
var type = element.type;
if (type == " checkbox" || type == "radio") {
if (element.checked != element.defaultChecked) {
return true;
}
}
else if (type ==🎜>}
}
else if (type == "hidden" || type == "password" || type == "text" || type == "textarea") {
if (element.value != element.defaultValue) {
return true;
}
}
else if (type == "select-one" || type == "select-multiple") {
for (var j = 0; j if (element.options[j].selected != element.options[j].defaultSelected) {
return true;
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
} } } } } } } } } } return false; } window.onbeforeunload = function(e) { e = e || window.event; if (formIsDirty(document.forms["someForm" ])) { if (e) { e.returnValue = "You have unsaved changes."; } return "You have unsaved changes."; } };