Reset all form elements using JavaScript
=============================
JavaScript has the ability to clear all form fields. HTML form has Reset method, but if the form has initial values, then Reset
will return the form to the initial state instead of clear input
fields. This example also shows how to create an access loop for each
form element. You can uncomment alert before "switch" line and you will
see the message before element value is cleared. Drop down select-one will be set to its first option because it can not be treated like input text field or select-multiple.
And the JavaScript source:
function clearForms() {
var x, y, z, type = null ;
for (x = 0; x < document.forms.length; x++) {
for (y = 0; y < document.forms[x].elements.length; y++) {
type = document.forms[x].elements[y].type;
switch (type) {
case 'text' :
case 'textarea' :
case 'password' :
document.forms[x].elements[y].value = '' ;
break ;
case 'radio' :
case 'checkbox' :
document.forms[x].elements[y].checked = '' ;
break ;
case 'select-one' :
document.forms[x].elements[y].options[0].selected = true ;
break ;
case 'select-multiple' :
for (z = 0; z < document.forms[x].elements[y].options.length; z++) {
document.forms[x].elements[y].options[z].selected = false ;
}
break ;
}
}
}
}
|
As script goes through all form elements on the HTML page, it will not clear only this test form, but
Search field and the
Message box also. So if you want to leave a comment, do not test the
Clear
button before you click on submit. On the other hand, if you want to
clear only group of input elements closed within DIV or some other HTML
tag, you will have to modify
clearForms() function and it can look like:
function clearElements(el) {
var x, y, z, type = null , object = [];
object[0] = document.getElementById(el).getElementsByTagName( 'input' );
object[1] = document.getElementById(el).getElementsByTagName( 'textarea' );
object[2] = document.getElementById(el).getElementsByTagName( 'select' );
for (x = 0; x < object.length; x++) {
for (y = 0; y < object[x].length; y++) {
type = object[x][y].type;
switch (type) {
case 'text' :
case 'textarea' :
case 'password' :
object[x][y].value = '' ;
break ;
case 'radio' :
case 'checkbox' :
object[x][y].checked = '' ;
break ;
case 'select-one' :
object[x][y].options[0].selected = true ;
break ;
case 'select-multiple' :
for (z = 0; z < object[x][y].options.length; z++) {
object[x][y].options[z].selected = false ;
}
break ;
}
}
}
}
|
You will have to assign ID to the parent element which contains input
elements. To clear input elements, function call should look
clearElements('myForm').