Piotr Ruszkiewicz
Piotr Ruszkiewicz

Reputation: 49

Clear Input filed after Form submit

I'm trying to clear input field after submitting with textcontent = '' but it won't work.

const inputField = document.querySelector('.input');
document.querySelector('.submit').addEventListener('click', function() {
    for (let i = 1; i <= 5; i++) {
        if (document.querySelector(`.position-${i}`).classList.contains('hidden')) {
            document.querySelector(`.position-${i}`).classList.remove('hidden')
            document.querySelector(`.text-${i}`).textContent = inputField.value
            document.querySelector('.input').textContent = ''
            if (!document.querySelector(`.position-${i}`).classList.contains('hidden')) break
        }
    }
})

Upvotes: 1

Views: 516

Answers (1)

Roko C. Buljan
Roko C. Buljan

Reputation: 205979

To reset a form use HTMLFormElement.reset()

const elForm = document.querySelector("#myForm");

elForm.addEventListener("submit", (evt) => {
  evt.preventDefault(); // Don't follow default form action

  elForm.reset(); // Reset form elements to default values

  // Remove class "hidden" from elements that have such class
  elForm.querySelectorAll(".hidden").forEach((elHidden) => {
    elHidden.classList.remove("hidden");
  });

});

Besides that,

the HTMLInputElement has no .textContent setter.
Use eventually .value instead (* read below about the implications of doing so)

// WARNING! Don't use this example to "reset" an input value!
document.querySelector('input').value = '';

but

  • such will only operate on the first <input> that's found in your app.
  • it will not reset the input value, rather it will override it to an empty string.

Instead, use .defaultValue:

To account for all your inputs of a specific form use:

document.querySelectorAll("#myForm input, #myForm textarea").forEach(elInp => {
  elInp.value = elInp.defaultValue;
});

You can also use HTMLFormElement.elements to iterate over a live HTMLFormControlsCollection:

const elForm = document.querySelector("#myForm");

// Let's modify the values on the fly
elForm.querySelector('[name="title"]').value = "222";
elForm.querySelector('[name="content"]').value = "Ipsum";

// Let's reset to their default values:
[...elForm.elements].forEach((el) => {
  el.value = el.defaultValue;
});
<form action="" id="myForm">
  <input name="title" type="text" value="123"><br>
  <textarea name="content">Lorem</textarea>
</form>

Again, that's useful to reset only specific elements. Otherwise use the Form's .reset() method.

Upvotes: 3

Related Questions