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:
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:
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:
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'