JavaScript reset() method

Ads
 

JavaScript reset() method

To illustrate reset() method of JavaScript we have created a simple HTML page into which we have created a form with the id "userform".

To illustrate reset() method of JavaScript we have created a simple HTML page into which we have created a form with the id "userform".

JavaScript reset() method

     

In JavaScript there are two ways to reset the given form as follows :

  • By using Reset button of HTML
  • By using reset() method of JavaScript

Example of Reset button :

<input type="reset" value="Reset" />

Example of reset() method :

 document.getElementById('formname').reset();

Syntax : Syntax for using reset() method is as given below :

 form_object.reset();

Where form_object is the reference to any form and method reset() will be applied on this form.

Description of code:

To illustrate reset() method of JavaScript we have created a simple HTML page into which we have created a form with the id "userform". Into this form we have taken two input fields "Name" and "Age". These fields are to be reset when the user clicks on the button "Reset all fields". It calls the function resetForm() defined in between <script></script> tags. Function is defined as below :

 function resetForm(){
   document.getElementById("userForm").reset();
 } 

In above lines of code we have first taken the reference to the form which is to be reset and thereafter we have used method reset() over it. Here is the full example code for resetExample.html :

<html>
<body>
<script language="JavaScript">
 function resetForm(){
   document.getElementById("userForm").reset();
 } 
</script>
<div style="background: #ff9900; width:'100%';"
            align="center">
  <font color="#0000ff" size="12pt">
	<b>Reset Example</b>
  </font>
 </div>
  <center>
    <div style="background: #0099ff; width:'100%';"
       align="center">
	<form id="userForm" >
	<p>Name <input type="text" id="txtname" /></p>
	<p>Age&nbsp;&nbsp;&nbsp;<input type="text"
                 id="txtage" /></p>
	<p> <input type="button" value="Reset all fields"
          onClick="resetForm()"/></p>
	</form>
    </div>
 </center>
</body>
</html>

Output :

Fill the form fields "Name" and "Age"

When you will click on the button "Reset all fields" it will reset all input entries.

Download Source Code

     

Ads

Ads