Clear form with JavaScript

More...

JavaScript is the only option, if you want to have the ability to clear all form fields. Yes, 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.

Text On the left is a simple form to show how this script works. Button Clear will clear form while button Reset will back form to the initial state. You can also change form values before test. Please try!
Textarea
Password
Radio
Checkbox
Select-one
Select-multiple 

And the JavaScript source:

// function will clear input elements on ever form on HTML page
function clearForms() {
	// variable declaration
	var x, y, z, type = null;
	// loop through forms on HTML page
	for (x = 0; x < document.forms.length; x++) {
		// loop through each element on form
		for (y = 0; y < document.forms[x].elements.length; y++) {
			// define element type
			type = document.forms[x].elements[y].type;
			// alert before erasing form element
			//alert('form='+x+' element='+y+' type='+type);
			// switch on element type
			switch (type) {
			case 'text':
			case 'textarea':
			case 'password':
			//case "hidden":
				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;
			} // end switch
		} // end for y
	} // end for x
}

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) {
	// variable declaration
	var x, y, z, type = null, object = [];
	// collect form elements
	object[0] = document.getElementById(el).getElementsByTagName('input');
	object[1] = document.getElementById(el).getElementsByTagName('textarea');
	object[2] = document.getElementById(el).getElementsByTagName('select');
	// loop through found form elements
	for (x = 0; x < object.length; x++) {
		for (y = 0; y < object[x].length; y++) {
			// define element type
			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;
			} // end switch
		} // end for y
	} // end for x
}

You will have to assign ID to the parent element which contains input elements. To clear input elements, function call should look clearElements('myForm').

This entry was posted on December 26, 2008 and is filed under JavaScript

Related posts

17 Responses to Clear form with JavaScript

  1. I am trying to clear the form inputs in WordPress.... any idea how to do that?

  2. dbunic says:

    Rashmi,
    I suppose that you want to clear comment input fields pre filled with name, mail and website. Hmm, I have an idea but you will have to modify your WordPress template. Please find and open comments.php file. Near the "Submit Comment" button add "Clear" button - like in this post. You should add a JavaScript clearForms() function also closed in <script type="text/javascript"> </script> tags. OnClick event of "Clear" button will call clearForms() function and comment input fields should be cleared.

  3. mario says:

    I am trying to setup a function that would clear input field values (textarea,checkbox,select menu etc) entered by users but only locally within a div tag, as each one represents a unique item with different options. any ideas?

  4. dbunic says:

    Mario,
    I updated this post and suggest solution for your need. Hope this will help.

  5. mario says:

    thank you so much! that did the job!

  6. dbunic says:

    You're welcome.

  7. Thanks Man! that's help me alot!

  8. Manjula says:

    Nice article. Thank you for sharing.

  9. Ravi says:

    Hi its nice article but how can I remove the list box items. I have the code as follows

    else if (FormName.elements[i].type == 'select-multiple') {
    	for (index = FormName.elements[i].options.length - 1; index >= 0; index--) {
    		FormName.elements[i].options.remove(index);
    	}
    }
    

    It is working fine in removing the elements but if i add new element after clearing, again previous elements are adding to the listbox...

  10. dbunic says:

    @Ravi - clearing form should not affect adding or removing options in select or multiple-select. Loop goes through all multiple-select options and sets "selected" property to "false". If options are deleted from multiple-select then "clear-form" loop should not add previously deleted items ...

  11. Sol says:

    This worked as a charm.. thanks a mil for sharing...

  12. writer jobs says:

    Thanks Man! that's help me a lot! If options are deleted from multiple-select then "clear-form" loop should not add previously deleted items ...

  13. harika says:

    I want code for clear a form before submit. Suppose if I enter anything wrong then I need to clear all fields in JavaScript.
    Please give reply fast.

  14. dbunic says:

    @harika - This clearForms() JavaScript function is exactly what you need. It will clear all form elements on the page. Just call clearForms() function in case of wrong input and form elements will be cleared.

    In the meantime, clearFields function is verified with JSLint - now code looks clean and correctly indented.

  15. ahmad balavipour says:

    Thanks a lot, very good code.

  16. Kala says:

    Can you please tell me how to clear the value if input type="file"

  17. dbunic says:

    @Kala - Well, <input type="file"> is the tricky one. Field value cannot be changed or reset (without doing a full form reset) for security reasons. Possible workaround could be to completely delete element from the form and to add it again - simply just replace it ;)

    Here is link to http://stackoverflow.com/ with suggested solution in jQuery but it can be without jQuery as well.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>