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

0

How can I make a textarea button on the page have its content deleted?

    
asked by anonymous 19.02.2018 / 04:07

2 answers

1

You can reset all fields using the reset() method. Here is 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

    
19.02.2018 / 04:24
1

You can also add a button or input element with 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 can not be changed this way, with only one 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>
    
19.02.2018 / 04:32