This example describes how JavaScript determines whether a user modifies a form. Share to everyone for your reference. The specific analysis is as follows:
This JS code can determine whether the user has changed the content of the form, if the form is modified, and exit the browser, it will remind the user whether to save the contents of the form, is very useful code.
function Formisdirty (form) {for
(var i = 0; i < form.elements.length; 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 = = "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 < Element.options.length; J +) {
if (element.options[j].selected!=
element.options[j].defaultselected) {return
true;
}
}}
}
return false;
}
Use Example: When you exit the browser, if the user modifies the form, remind the user if they want to save
Window.onbeforeunload = function (e) {
e = e | | window.event;
if (Formisdirty (document.forms["Someform"])) {
//for IE and Firefox
if (e) {
E.returnvalue = ' You have Unsave D changes. ";
}
For Safari return
' you have unsaved changes. '
}
};
The following is a complete sample code
Copy Code code as follows:
Click on below button. Now change some values in form and click the button again.
<form name= "Fooform" >
<input type= "text" name= "T" ><br>
<input type= "Text" name= "2" value= "Default" ><br>
<select name= "some" >
<option value= "fooo" selected= "" >foo</option>
<option value= "Bar" >bar</option>
</select><br>
</form>
<button onclick= "alert (Formisdirty (document.fooform))" >click to check if Form is dirty</button>
<br>
<script>
function Formisdirty (form) {
for (var i = 0; i < form.elements.length; 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 = = "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 < Element.options.length; J + +) {
if (element.options[j].selected!=
element.options[j].defaultselected) {
return true;
}
}
}
}
return false;
}
</script>
I hope this article will help you with your JavaScript programming.