简体   繁体   English

清除表单提交后提交的输入

[英]Clear Input filed after Form submit

Im trying to clear input field after submitting with textcontent = '' but it won't work.我试图在使用 textcontent = '' 提交后清除输入字段,但它不起作用。

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
    }
}

}) })

To reset a form use HTMLFormElement.reset()要重置表单,请使用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. HTMLInputElement没有.textContent设置器。
Use eventually .value instead (* read below about the implications of doing so)最终使用.value代替(*阅读下面有关这样做的含义)

// 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.这样只会在您的应用程序中找到的第一个<input>上运行。
  • it will not reset the input value, rather it will override it to an empty string.不会重置输入值,而是会将其覆盖为空字符串。

Instead, use .defaultValue :相反,使用.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:您还可以使用HTMLFormElement.elements迭代实时 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.否则使用表单的.reset()方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM