Clear form with JavaScript

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’).

27 thoughts on “Clear form with JavaScript”

  1. 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.

  2. 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?

  3. 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…

  4. @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 …

  5. 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 …

  6. 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.

  7. @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.

  8. @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.

  9. I’m working on an online exam which, after a person takes the quiz and clicks the “check quiz” button, displays the correct answers (true/false) by highlighting them in a color.

    var highlightColor = "#FF3";
    
    function highlightCorrectButton(radioButton)  {
       document.getElementById(radioButton).style.backgroundColor = highlightColor;
    
    function checkQuiz() {
       highlightCorrectButton('correct1');
    
    etc....
    

    If they want to take the quiz again, how do I clear the color, along with the selected radio buttons? The code example above clears the answers perfectly, but the correct answers remain highlighted. I have the correct radio buttons wrapped in a tag, and it works great. I just need to figure out how to clear the color of that tag or element when a person clicks on the “clear” button. Any help? It’s probably simple, but I do not know JavaScript at all, so any help is appreciated.

  10. @Carley – You can remove inline styles along with resetting form on the following way:

    ...
    case 'radio':
    case 'checkbox':
        document.forms[x].elements[y].checked = '';
        document.forms[x].elements[y].style.backgroundColor = '';
        break;
    ...
    

    Try to add the marked line to the “checkbox” case. Previously assigned background color should be deleted.
    Hope this tip will help you. Cheers!

  11. I want to clear the text box values, ie; user has edited the textbox and entered a text, need to clear only the entered the text box…

    Please help me over this problem.

    Thanks in advance…

    Thankyou MR.Dbunic for the Awesome Code…!

Leave a Comment