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}
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}