How to Reset Form in JavaScript

Mehvish Ashiq Feb 02, 2024
  1. Reset Form in JavaScript Without jQuery
  2. Reset Form in JavaScript With jQuery
How to Reset Form in JavaScript

This tutorial will teach us how to reset form in JavaScript with and without using jQuery. The reset() method restores the form elements to default values.

The reset() method in JavaScript functions the same as the HTML reset button.

The following HTML code remains the same for all the JavaScript code examples.

<!DOCTYPE html>
<html>
	<body>
		<p>
      		fill the text boxes with some text content and press the "Reset form" button to reset the form.
    	</p>
		<form id="form">
  			First name: <input type="text" name="firstname"><br>
  			Last name: <input type="text" name="lastname"><br><br>
 			<input type="button" onclick="resetForm()" value="Reset form">
		</form>
	</body>
</html>

Reset Form in JavaScript Without jQuery

JavaScript Code:

function resetForm() {
  document.getElementById('form').reset();
}

Output:

reset form in javascript - reset form without jquery

The upper solution is pure JavaScript. The resetForm() function is executed when the Reset form button clicks.

The reset() method neither takes parameters nor returns any value.

Reset Form in JavaScript With jQuery

Remember to include the jQuery library in the <head> element to practice the following code example.

JavaScript Code:

function resetForm() {
  $('#form').trigger('reset')
}

Output:

reset form in javascript - reset form with jquery part one

The above solution is achieved with jQuery. The trigger() function triggers the particular event and the event’s default behavior (like form submission) for picked-out elements.

The trigger() method resembles the triggerHandler() function, except that triggerHandler() does not trigger the event’s default behavior.

Following is another solution in jQuery that we can use. It is the reflection of document.getElementById("form").reset();.

JavaScript Code:

function resetForm() {
  $('#form')[0].reset();
}

Output:

reset form in javascript - reset form with jquery part two

Remember that the reset() method does not work if any of the form’s fields has an attribute name="reset". It gives you the following error.

'<a class=\'gotoLine\' href=\'#55:17] Uncaught TypeError: $(...)[0\'>55:17] Uncaught TypeError: $(...)[0</a>.reset is not a function'
Mehvish Ashiq avatar Mehvish Ashiq avatar

Mehvish Ashiq is a former Java Programmer and a Data Science enthusiast who leverages her expertise to help others to learn and grow by creating interesting, useful, and reader-friendly content in Computer Programming, Data Science, and Technology.

LinkedIn GitHub Facebook

Related Article - JavaScript Form