Reset form values in html

Using JavaScript to reset or clear a form

Using an HTML ‘Reset’ button is an easy way to reset all form fields to their default values. For instance, the code snippet below shows an field of type “reset”, which on being clicked resets all the form fields:

input type="reset" value="Reset Form"> 

In fact, we could also use the form’s reset() method to achieve the same effect, using a simple button element:

input type="button" value="Reset Form" onClick="this.form.reset()" /> 

These methods are very convenient to use, but they do not provide the functionality of clearing all the fields, including their default values. In order to achieve this, we would need to write a JavaScript function that would clear each individual field’s value.

Simple example for clearing all form elements using JavaScript

Let us look at an example of a simple form

form name="data_entry" action="#">  Company Name: input type="text" size="35" name="company_name">  Select Business Type: input type="radio" name="business_category" value="1"> Manufacturer input type="radio" name="business_category" value="2"> Whole Sale Supplier input type="radio" name="business_category" value="3"> Retailer input type="radio" name="business_category" value="4"> Service Provider  Email Address: input type="text" size="30" name="email">  Keep Information Private: input type="checkbox" name="privacy">  input type="button" name="reset_form" value="Reset Form" onclick="this.form.reset();">  input type="button" name="clear" value="Clear Form" onclick="clearForm(this.form);">  form> 

As you can see, the first button simply resets all the fields using this.form.reset() as described earlier. Let us now write the JavaScript function that behaves as the onClick handler for the second button in the above form.

  1. In this function, we would first need to acquire a reference to all the elements in the form object:
var frm_elements = oForm.elements; 

where, oForm is a reference to the form object passed to the function using this.form as shown in the form above. oForm.elements is now a Javascript array that holds a reference to each of the form elements.

  1. We would then have to iterate over the individual form element objects of the frm_elements array (Step 1), using a for-loop construct:
for(i=0; ifrm_elements.length; i++)   // code for accessing each element goes here  > 
  1. We can find out the type of each form element in the frm_elements array by retrieving it’s type property:
field_type = frm_elements[i].type.toLowerCase(); 
  1. If frm_elements[i] holds a reference to any of the , , and elements, it’s value can be cleared by simply setting it to an empty string:

In case of radio and checkbox elements, we would use a different approach:

 if (frm_elements[i].checked)   frm_elements[i].checked = false; > 

If frm_elements[i] is an object of the type select (either select-one or select-multi), we can set the selectedIndex property to -1:

frm_elements[i].selectedIndex = -1; 
 for (i = 0; i  frm_elements.length; i++)   field_type = frm_elements[i].type.toLowerCase();  switch (field_type)    case "text":  case "password":  case "textarea":  case "hidden":  frm_elements[i].value = "";  break;  case "radio":  case "checkbox":  if (frm_elements[i].checked)    frm_elements[i].checked = false;  >  break;  case "select-one":  case "select-multi":  frm_elements[i].selectedIndex = -1;  break;  default:  break;  > > 

Have a look at the demo to see how it works, and compare the result of clicking the reset button and the button with the custom onClick handler that we have just coded. You can also download the code from here.

Illustrating the difference between resetting and clearing a form

As the above demo illustrates, the two buttons function similarly, for this particular form, because none of the values of the elements in this form are set on page load. So the difference between the functioning of the two buttons is not visible. Let us set default values for some of the form elements. For instance, the following snippet of code sets the default for the radio element named “business_category” to the value 3.

 input type="radio" name="business_category" value="1">Manufacturer input type="radio" name="business_category" value="2">Whole Sale Supplier input type="radio" name="business_category" value="3" checked>Retailer input type="radio" name="business_category" value="4">Service Provider 

Likewise, we can also set defaults for a few other form elements. See this demo, for an example and compare it with the previous one. As you must have noticed, the difference is now obvious, as the Reset button does not clear the default values, unlike the other button, which does.

See Also

Источник

Form reset() Method

The reset() method resets the values of all elements in a form (same as clicking the Reset button).

Tip: Use the submit() method to submit the form.

Browser Support

The numbers in the table specify the first browser version that fully supports the method.

Method
reset() Yes Yes Yes Yes Yes

Syntax

Parameters

Return Value

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

Reset HTML Form After Submission (Simple Examples)

Welcome to a quick beginner’s tutorial on how to reset an HTML form after submission. So you are working on a form that needs to be cleared after the user submits it?

  1. Use document.getElementById(«FORM»).reset() in Javascript to reset the form.
  2. Add an autocomplete=»off» property to the HTML form to prevent possible auto-filling after the form reset.

That covers the basics, but let us walk through a few examples in this guide – Read on!

TLDR – QUICK SLIDES

Reset HTML Form After Submission

TABLE OF CONTENTS

FORM RESET

All right, let us now get into the examples of resetting the form after submission.

EXAMPLE 1) AUTOCOMPLETE OFF

First, this is nothing but a simple HTML form with autocomplete=»off» . What has this got to do with resetting forms? Heard of “autocomplete” or “autofill”? This modern convenience can be a stupid pain when resetting forms – You reset the form, and autocomplete fills them back. Genius.

So yes, autocomplete=»off» is optional, but recommended. Take note though, this is not a directive but more of a recommendation. Browsers and plugins can still ignore and do the form autocomplete.

EXAMPLE 2) AJAX FORM SUBMIT & RESET

2A) HTML FORM

2B) THE JAVASCRIPT

function process () < // (A) GET FORM DATA var form = document.getElementById("my-form"), data = new FormData(form); // (B) AJAX SEND FORM // NOTE: USE HTTP://. NOT FILE://. fetch("x-dummy.txt", < method: "POST", body: data >) .then(res => res.text()) .then(txt => < console.log(txt); form.reset(); // reset form >); // (C) STOP DEFAULT FORM SUBMIT/PAGE RELOAD return false; >

This may throw the absolute beginners off a little bit because we are not submitting the form in the “traditional way”. This is called Asynchronous Javascript And XML (AJAX), in short, submitting the form without reloading the page. Now, it may seem to be a small handful at first, but it is very straightforward.

  1. First, get the HTML form var form = document.getElementById(«my-form») . Then, collect the form data data = new FormData(form) .
  2. We use fetch(URL, < method: "POST", body: data >) to send the form to the server via an AJAX call.
    • .then(res => res.text()) Returns the server response as plain text.
    • .then(txt =>< DO SOMETHING >) Do something with the server response. In this simple example, we use form.reset() to reset the form.

There, it’s not really that difficult.

EXAMPLE 3) PARTIAL FORM RESET

3A) HTML FORM

 Email: Password: Confirm Password:

A dummy HTML form as usual, but this time with 3 fields – Email, password, and confirm password. After submitting, we will reset the password fields, but leave the email be.

3B) THE JAVASCRIPT

function process () < // (A) GET FORM DATA var data = new FormData(document.getElementById("my-form")); // (B) AJAX SEND FORM fetch("x-dummy.txt", < method: "POST", body: data >) .then(res => res.text()) .then(txt => < console.log(txt); document.getElementById("user-password").value = ""; // reset password document.getElementById("confirm-password").value = ""; // reset confirm password >); // (C) STOP DEFAULT FORM SUBMIT/PAGE RELOAD return false; >

This is pretty much the same old AJAX process. But to partially reset a form, there is sadly no quick way around it. We have to manually get the fields and reset their values one by one.

DOWNLOAD & NOTES

Here is the download link to the example code, so you don’t have to copy-paste everything.

SUPPORT

600+ free tutorials & projects on Code Boxx and still growing. I insist on not turning Code Boxx into a «paid scripts and courses» business, so every little bit of support helps.

EXAMPLE CODE DOWNLOAD

Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.

INFOGRAPHIC CHEAT SHEET

THE END

Thank you for reading, and we have come to the end of this guide. I hope that it has helped you with your project, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

Leave a Comment Cancel Reply

Breakthrough Javascript

Take pictures with the webcam, voice commands, video calls, GPS, NFC. Yes, all possible with Javascript — Check out Breakthrough Javascript!

Socials

About Me

W.S. Toh is a senior web developer and SEO practitioner with over 20 years of experience. Graduated from the University of London. When not secretly being an evil tech ninja, he enjoys photography and working on DIY projects.

Code Boxx participates in the eBay Partner Network, an affiliate program designed for sites to earn commission fees by linking to ebay.com. We also participate in affiliate programs with Bluehost, ShareASale, Clickbank, and other sites. We are compensated for referring traffic.

Источник

Читайте также:  Xml парсер для java
Оцените статью