Clear controls in javascript

How to reset or clear a form using JavaScript?

This tutorial teaches us how to reset or clear a form using JavaScript. This option is very helpful for users in the situation where they have filled the wrong form and before submitting they get to know about it and now they want to delete all the data. If the form is too large then manually deleting everything may be hard so it’s better to use the reset() method of JavaScript.

The reset() method is defined in JavaScript and by just clicking on it the form which will be linked to its onclick() method will reset every input section of the provided form.

Syntax

We have seen the basics of the reset() function, now let’s move to its syntax −

var element = document.getElementById( Id_of_required_form ). element.reset()

In the above syntax, “Id_of_required_form” is the id of the form which we want to reset or clear. We have used the ‘getElementById’ method of the DOM to get the form and stored that in a variable name ‘element’.

After that, by using the method reset() we reset or clear the form with the id ‘Id_of_required_form’ element by calling it.

Algorithm

We have seen the syntax to reset or clear a form by getting its id and reset() method, let’s see the complete algorithm step by step to understand it in a better way −

Creating a user form

In these steps, we will create the form in which we will define or create many input boxes for user input to fill the form and a button which will call the function to delete the object from the dropdown list.

  • Initially, we have to create a form using the tag which we want to reset or clear using the reset() method of JavaScript.
  • In the form, we have created some input boxes by using the tag where the user can write the data.
  • These input spaces will be of type text and number to get the user input in the required type.
  • In the form after defining ‘inputs’ to take user input, we will define an input field using the tag and will make it of type button and we will define the ‘onclick’ event which will call the function which we will define later in the script.

Defining script or function to remove

In these steps, we will define the function which will be called in the ‘onclick’ event of the above-defined button.

  • Initially, we will create a function using the ‘function’ keyword and will give it a name that will be called in the ‘onclick’ event.
  • In the defined function we will create a variable to store the return value from the call to the ‘document.getElementById()’ method.
  • We will pass the ‘id’ of the above-defined form as the parameter to the call to the ‘document.getElementById()’ method.
  • By using the reset method with the variable (which contains the return value of the call to the method) we can reset every input field to empty.
Читайте также:  You should add extension mcrypt so to php ini

These are the basic steps to reset or clear a form using JavaScript, now let’s see some examples to get a better understanding of the above-defined steps.

Example

In this example, we are going to implement the above-defined algorithm step by step, let’s implement the code −

!DOCTYPE html> html> body> h3>Fill out the below-given form and click the reset button to see the working of the reset() function in JavaScript./h3> form id=" form_id "> Student Name br> input type="text" name="sname"> br> Student Subject br> input type = "password" name = "ssubject" > br> Student Roll Number br> input type = "roll_no" name = "roll_number" > br> input type = "button" onclick = "newFunction()" value = "Reset" > /form> script> function newFunction() var element = document.getElementById(" form_id "); element.reset() > /script> /body> /html>

In the above output, we got one form in which there are some input spaces, where the user can provide some input and at last, there is a reset button which will reset the form to the original or initial form.

Conclusion

In this tutorial, we have learned the method to reset or clear the HTML form using JavaScript. This is only possible if while defining the HTML form programmer defines or creates a button for the user to reset the form otherwise the user has to reset it manually.

The reset() function is defined in JavaScript and by just clicking on it the form which will be linked to its onclick() method will reset every input section of the provided form. Also, if there is any pre-defined value is there present for any input it will get that value.

Источник

How to Clear Input Fields in JavaScript

There can be a situation where it is required to clear the entered value of an input field or the whole form. For instance, you need to change the category or encounter a specific requirement to change all of the entered data. In such cases, clearing input fields using JavaScript becomes very effective and useful.

This article will discuss the methods to clear the input fields in JavaScript.

How to Clear Input Fields in JavaScript?

To clear input fields in JavaScript, the following approaches can be utilized:

Go through the discussed methods one by one!

Method 1: Clear Input Fields in JavaScript Using onfocus Event and target Property

The “onfocus” event is triggered when a specific element gets focus, and the “target” property returns the element that triggered the event. More specifically, these techniques can be applied to clear the specified target value in the input field.

The following example explains the discussed concept clearly.

Example

In the following example, we will assign an input type as “text” with the specified value and and attach as onfocus event to it which will trigger the clearInput() function:

Now, define the function named “clearInput()” with the “target” property as its argument in order to return the element that triggered the event. After that, a specific condition will be applied that if the input field hold a particular value, such as “clear input”, the input field will be cleared:

Now, when the user will input “clear input” value in the input field and it gets focus, the entered value will get clear:

Method 2: Clear Input Fields in JavaScript Using onclick Event and document.getElementById() Method

In JavaScript, the “document.getElementById()” method is utilized for accessing an element based on its id and “onclick” is used to attach an event to an HTML element. More specifically, this combination can be used in such a way when the added button is clicked, the input field element will be accessed, and the entered value will be cleared.

Example

Firstly, assign an input type with an id named as “name”:

Then, create a button with a value named “clear” and add an “onclick” event which will access the clearInput() function when triggered:

Now, define a function named “clearInput()”. Here, the document.getElementbyId() will access the input field using its id. Then, an “if” condition will be applied so that as long as the input field is not empty, the value of the input field will be set as empty:

function clearInput ( ) {
var getValue = document. getElementById ( «name» ) ;
if ( getValue. value != «» ) {
getValue. value = «» ;
}
}

In this scenario, clicking the added button will clear the input field value:

Want to reset all input field values at once? Check out the next method.

Method 3: Clear Input Fields in JavaScript Using reset() Method

The “reset()” method clears all the values of the form elements. This method can be implemented to clear the input field holding text with a click of a button.

Syntax

Here, “formObject” is the element that will be reset.

Have a look at the given example.

Example

First, create a form and assign it an id as demonstrated below. Next, ask the user to enter an “ID” in the input field. Then, include a button with an “onclick” event accessing a function as discussed in the previous method:

Finally, declare a function named “clearInput()”, fetch the form using the document.getElementById() method and reset the input field upon the button click:

Output

We have demonstrated the techniques to clear input fields in JavaScript.

Conclusion

To clear input fields in JavaScript, utilize the “onfocus” event and “target” property to apply the functionality based on the presence of a particular value, or the “onclick()” event and “document.getElementById()” method for getting the id of the input field and clearing the field as long as there is some value in it or the “reset()” method to reset the values of all input field at once. This write-up has explained the methods to clear the specified input fields in JavaScript.

About the author

Sharqa Hameed

I am a Linux enthusiast, I love to read Every Linux blog on the internet. I hold masters degree in computer science and am passionate about learning and teaching.

Источник

Clear controls in javascript

Last updated: Jan 12, 2023
Reading time · 3 min

banner

# Table of Contents

# Clear an Input field after Submit

To clear an input field after submitting:

  1. Add a click event listener to a button.
  2. When the button is clicked, set the input field’s value to an empty string.
  3. Setting the field’s value to an empty string resets the input.

Here is the HTML for this example.

Copied!
DOCTYPE html> html lang="en"> head> title>bobbyhadz.comtitle> meta charset="UTF-8" /> head> body> input type="text" id="first_name" name="first_name" /> button id="btn" type="submit">Submitbutton> script src="index.js"> script> body> html>

And here is the related JavaScript code.

Copied!
const btn = document.getElementById('btn'); btn.addEventListener('click', function handleClick(event) // 👇️ if you are submitting a form (prevents page reload) event.preventDefault(); const firstNameInput = document.getElementById('first_name'); // Send value to server console.log(firstNameInput.value); // 👇️ clear input field firstNameInput.value = ''; >);

We added a click event listener to the button.

Every time the button is clicked, the handleClick function is invoked, where we set the value of the input to an empty string.

# Clear multiple input fields after submit

To clear the values for multiple inputs after submitting:

  1. Use the querySelectorAll() method to select the collection.
  2. Use the forEach() method to iterate over the results.
  3. Set the value of each input field to an empty string to reset it.
Copied!
DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> title>bobbyhadz.comtitle> head> body> input type="text" id="first_name" name="first_name" /> input type="text" id="last_name" name="last_name" /> button id="btn" type="submit">Submitbutton> script src="index.js"> script> body> html>

And here is the related JavaScript code.

Copied!
const btn = document.getElementById('btn'); btn.addEventListener('click', function handleClick(event) // 👇️ if you are submitting a form event.preventDefault(); const inputs = document.querySelectorAll('#first_name, #last_name'); inputs.forEach(input => input.value = ''; >); >);

We used the document.querySelectorAll method to select a NodeList containing the elements with IDs set to first_name and last_name .

The method takes a string that contains one or more valid CSS selectors.

The function we passed to the NodeList.forEach method gets invoked with each input in the NodeList .

In the function, we set the value of each input to an empty string.

# Clear all form fields after submitting

To clear all form fields after submitting:

  1. Add a submit event listener on the form element.
  2. When the form is submitted, call the reset() method on the form.
  3. The reset method restores the values of the input fields to their default state.

Here is the HTML for this example:

Copied!
DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> title>bobbyhadz.comtitle> head> body> form action="" id="my_form"> input type="text" id="first_name" name="first_name" /> input type="text" id="last_name" name="last_name" /> button id="btn" type="submit">Submitbutton> form> script src="index.js"> script> body> html>

And here is the related JavaScript code.

Copied!
const form = document.getElementById('my_form'); form.addEventListener('submit', function handleSubmit(event) event.preventDefault(); // 👇️ Send data to the server here // 👇️ Reset the form here form.reset(); >);

We added a submit event listener to the form element.

The event fires when a form is submitted.

We used the event.preventDefault() method to prevent the page from reloading.

The reset() method restores a form’s elements to their default values.

If you need to show/hide a form on button click, check out the following article.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Оцените статью