In HTML, the reset button serves the purpose of restoring a form to its original state. This article will explore the methods for resetting a form utilizing JavaScript.
In JavaScript, the reset function performs the identical action as the reset button found in HTML forms. Its primary purpose is to clear all the values entered in the form fields. This method can effectively restore the values to their original defaults. Notably, it does not accept any parameters, nor does it produce a return value.
Syntax
formElement.reset()
Example
To demonstrate the functionality of the reset method in JavaScript, we will construct a straightforward HTML document that contains a form identified by the id = "myForm". This form comprises four text input fields labeled: "First Name", "Last Name", "Age", and "E-mail Id". Additionally, there are two buttons labeled "Submit" and "Reset data". Upon clicking the Reset data button, the function fun is invoked, within which the reset method from JavaScript is implemented.
Within the function fun, we initially obtain a reference to the form that needs to be reset, and subsequently, we invoke the reset method on that reference. Now, let’s examine the corresponding code for this process.
<!DOCTYPE html>
<html>
<head>
<title> reset() method </title>
</head>
<body style = "text-align: center;">
<div style = "background: pink;">
<font color = "red" size = "6px">
<b> Example of the reset() method </b>
</font>
</div>
<div style = "background: lightblue;">
<form id = "myForm" action = "#" style = "font-size: 20px;" >
<p> First Name: <input type = "text" id = "fname" /></p>
<p> Last Name: <input type = "text" id = "lname" /></p>
<p> E-mail Id: <input type = "email" id = "email" /></p>
<p> Age: <input type = "number" id = "age" /></p>
<input type = "submit">
<input type = "button" value = "Reset data" onClick = "fun()"/>
</form>
</div>
<script>
function fun(){
document.getElementById("myForm").reset();
}
</script>
</body>
</html>
Output
Upon running the code provided above, the resulting output will be -
Now, let's fill the textfield values -
Ultimately, upon selecting the Reset data button, the values will be reverted to their original state -