| by Arround The Web | No comments

How to Use the HTML DOM Form reset() Method in JavaScript

The DOM(Document Object Model) comes with the form object “reset()” method in JavaScript to remove all the text from the corresponding input fields. It helps in clearing the input field if the user enters the wrong information into it. It is basically used to clear the data in all the input fields in the case of large forms in which the data deletion of each field is challenging.

This blog elaborates on the working of the HTML DOM Form “reset()” method in JavaScript.

How to Use the HTML DOM Form “reset()” Method in JavaScript?

The “reset()” method clears or resets all the values of the input fields. It also assists the users to remove the specified or all the data in the corresponding input field effectively.

Syntax

formObject.reset()

 
In the above syntax, the “formObject” acts as a container that contains various input fields.

Example: Applying the HTML DOM Form “reset()” Method to Reset the Data in the Form Input Fields

This example carries out the practical implementation of the “reset()” method to reset the entered data in form input fields.

HTML Code

First, have a look at the following HTML code:

<h2>Form reset() Method in JavaScript</h2>
<form id="form1">
 Name: <input type="text"><br>
 Grade: <input type="text"><br>
 Section: <input type="text"><br><br>
 <p>Click on the Reset button to clear all input fields.</p>
 <input type="button" onclick="myFunc()" value="Reset All">
</form>

 
In the above code snippet:

    • The “<h2>” tag corresponds to the subheading.
    • The “<form>” tag creates a form with an assigned id “form1”.
    • In the body section of the “form” element, the “<input>” tags add multiple input fields of type “text” to enter the desired text in them.
    • After that, the “<p>” tag specifies the stated paragraph statement.
    • Lastly, the “<input>” tag creates a button having an attached “onclick” mouse event to execute the function “myFunc()”. Also, the stated “value” is assigned referring to the button name.

JavaScript Code

Next, follow the below-stated code:

<script>
function myFunc() {
 document.getElementById("form1").reset();
}
</script>

 
According to the above code lines, the user-defined function “myFunc()” applies the “getElementById()” method to access the included “<form>” element via its id “form1” and resets all input fields via the “reset()” method.

Output


As seen, all the given input text fields are cleared via the “reset()” method upon triggering the “Reset All” button.

Conclusion

JavaScript uses the “reset()” method to remove the content from the input fields upon the user action. This method is helpful to clear all input fields and the desired one by simply clicking the button. This blog demonstrated the use of the HTML DOM Form “reset()” method in JavaScript.

Share Button

Source: linuxhint.com

Leave a Reply