Form中的每個對象都保留了初始值,所以可以在提交表單時,遍曆Form中對象,
檢查對象當前的值與初始值是否一致,就判斷出了表單是否被修改了。
範例程式碼
1function IsFormChanged()
2{
3 var isChanged = false;
4 var form = document.forms[0];
5 for (var i = 0; i < form.elements.length; i++)
6 {
7 var element = form.elements[i];
8 var type = element.type;
9 if (type == "text" || type == "hidden" || type == "textarea" || type == "button")
10 {
11 if (element.value != element.defaultValue)
12 {
13 isChanged = true;
14 break;
15 }
16 }
17 else if (type == "radio" || type == "checkbox")
18 {
19 if (element.checked != element.defaultChecked)
20 {
21 isChanged = true;
22 break;
23 }
24 }
25 else if (type == "select-one")
26 {
27 for (var j = 0; j < element.options.length; j++)
28 {
29 if (element.options[j].selected != element.options[j].defaultSelected)
30 {
31 isChanged = true;
32 break;
33 }
34 }
35 }
36 else
37 {
38 //
39 }
40 }
41
42 return isChanged;
43}