Categories
JavaScript Answers

How to reset hidden form fields with JavaScript?

Spread the love

Sometimes, we want to reset hidden form fields with JavaScript.

In this article, we’ll look at how to reset hidden form fields with JavaScript.

How to reset hidden form fields with JavaScript?

To reset hidden form fields with JavaScript, we can hide the form fields with CSS instead of setting their type to hidden.

Then we can reset them like any other form field.

For instance, we write:

<form id="f">
  <input style='display: none' name="foo" value="bar" />
  <input type='reset'>
</form>

to add a form with an input hidden with CSS and a reset button input.

Then we write:

const f = document.getElementById('f');
const reset = document.querySelector('input[type="reset"]');

reset.onclick = () => {
  f.reset()
}

to select the form and the input respectively.

Then we set the reset.onclick property to a function that calls f.reset to reset the form field values.

Conclusion

To reset hidden form fields with JavaScript, we can hide the form fields with CSS instead of setting their type to hidden.

Then we can reset them like any other form field.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *