How to Reset Button in JavaScript

Shraddha Paghdar Feb 02, 2024
How to Reset Button in JavaScript

This article will learn how to reset the form using JavaScript’s reset button.

Use reset to Reset the Form in JavaScript

Forms are used on web pages to fill in the required details, then sent to the server for processing. A form is also called a web form or an HTML form.

Examples of forms used are widely used on e-commerce websites, online banking, and surveys, to name a few.

Typical form control objects include the following:

  1. A text box for typing a line of text.
  2. A pushbutton for selecting an action.
  3. A radio button for making a selection from a group of options.
  4. A checkbox for enabling or disabling a single, independent option.

The reset-type input elements appear as buttons, with a default click event handler resets all form inputs to their initial values. This input element only supports two attributes: the type and the value.

Value is an optional attribute. One important thing to ensure is that the input element is inside the form element; otherwise, it won’t work.

It takes no parameter value and returns no value. It can be used to set default values.

Example:

<form name="form1">
  <input type='text' id="phoneNumber" name='text1'/>
  <input type="reset" onclick="resetForm()" value="Reset form"/>
  <button type="submit" name="submit" onclick="submitForm()">Submit</button>
</form>
function submitForm() {
  console.log('Form submitted');
}

function resetForm() {
  console.log('Reset form');
}

We have defined the form element in the above code, which takes the first name as an input.

We have given two buttons: the reset button will clear out the form, and the submit button will submit the entire form to the server to further process it.

Output:

Reset button in JavaScript Before

Reset button in JavaScript After

If you like to create a custom button and customize the behavior with JavaScript, you must use <input type="button">, or even better, a <button> element. JavaScript also provides an inbuilt reset() method that resets the entire form.

You can select the form element through its Id and reset it using reset(). See the reset method documentation for more information.

Shraddha Paghdar avatar Shraddha Paghdar avatar

Shraddha is a JavaScript nerd that utilises it for everything from experimenting to assisting individuals and businesses with day-to-day operations and business growth. She is a writer, chef, and computer programmer. As a senior MEAN/MERN stack developer and project manager with more than 4 years of experience in this sector, she now handles multiple projects. She has been producing technical writing for at least a year and a half. She enjoys coming up with fresh, innovative ideas.

LinkedIn