Reset all fields (input, textarea) of the html page

Asked

Viewed 304 times

0

How can I make that through a button all the textarea of the page has its content deleted?

2 answers

1


You can reset all fields using the method reset(). Follow a simple example.

function myFunction() {
  document.getElementById("myForm").reset();
}
<form id="myForm">
  Primeiro nome: <input type="text" name="fname"><br> Último nome: <input type="text" name="lname"><br><br>
  <input type="button" onclick="myFunction()" value="Resetar form">
</form>

Source: w3schools.com

  • the same does not work for textarea? textarea also would not form? Because I tested in my textarea and does not recognize this function.

1

You can also add an element button or input with the type="reset". Example:

<form id="myForm">
  Primeiro nome: <input type="text" name="fname"><br>
  Último nome: <input type="text" name="lname"><br><br><br>
  <button type="reset">Resetar form</button>
</form>

The textarea, input:checkbox, input:radio and select cannot be changed this way, only with a JS function.

Example:

const form = document.querySelector("#myForm");
const reset = document.querySelector("#reset");

reset.addEventListener("click", () => {
  form.querySelectorAll("select,input,textarea").forEach((el) => {

    switch (true) {
      case el instanceof HTMLTextAreaElement:
        el.textContent = "";
      break;
      case el instanceof HTMLSelectElement:
        el.querySelectorAll("option").forEach( (el) => el.removeAttribute("selected"))
      break;
      case el.type == "checkbox":
      case el.type == "radio":
        el.removeAttribute("checked");
      break;
      default:
        el.value = "";
    }
  })
});
<form id="myForm">
  Primeiro nome: <input type="text" name="fname"><br> Último nome: <input type="text" name="lname"><br>
  <textarea id="txt" name="txt">txt</textarea><br><br>
  <input type="checkbox" name="chk" checked />
  <input type="radio" name="radio" checked />
  <select name="select">
    <option value="Selecione algo">Selecione algo</option>
    <option value="1">1</option>
    <option value="2" selected>2</option>
    <option value="3">3</option>
  </select>
  

  <button type="reset" id="reset">Resetar form</button>
</form>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.