Clearing form fields

4

I have the following encoding and would like to clear the form from all fields that have the same name . But I do not know why it does not clear the fields
PS: What properties of input text can I use for this kind of thing?

function limpaCampos() {
  document.getElementsByName("form_txt").value = ''; // Limpa o campo
      console.log(document.getElementsByName("form_txt").value);
}
<html>
  <body>
    <input id="01" type="text" name="form_txt"/>
    <input id="01" type="text" name="form_txt"/>
    <input type="button" onclick="limpaCampos();"/>
  </body>
</html>
    
asked by anonymous 17.05.2018 / 20:47

3 answers

4

I'm not exactly sure if there's any way to change all the elements at once. One way I know to solve is to individually change in a loop .

In the example below, I store all HTML elements that contain the same name in a variable, and I used a forEach in this variable to clean each of them one at a time.

function limpaCampos() {
  var elements = document.getElementsByName("form_txt");
  elements.forEach(element => {
    console.log(element);
    element.value = '';
  })
}
<html>
  <body>
    <input id="01" type="text" name="form_txt"/>
    <input id="02" type="text" name="form_txt"/>
    <button type="button" onclick="limpaCampos();">Limpar</button>
  </body>
</html>
    
17.05.2018 / 21:08
2

You can use for to scroll through all fields and change value to empty:

function limpaCampos() {
  var campos = document.getElementsByName("form_txt");
  for(var x=0; x<campos.length; x++){
     campos[x].value= '';
  }
}
<input id="01" type="text" value="abc" name="form_txt"/>
<input id="01" type="text" value="def" name="form_txt"/>
<input type="button" value="limpar" onclick="limpaCampos();"/>
  

I also noticed that it uses the same id in both fields. This is incorrect.   A id must be unique on the page.

On the other hand I also did not understand the use of the same name in more than a input type text , except if you wanted to create an array, hence the name would have to be: name="form_txt[]" :

function limpaCampos() {
  var campos = document.getElementsByName("form_txt[]");
  for(var x=0; x<campos.length; x++){
     campos[x].value= '';
  }
}
<input id="01" type="text" value="abc" name="form_txt[]"/>
<input id="01" type="text" value="def" name="form_txt[]"/>
<input type="button" value="limpar" onclick="limpaCampos();"/>
    
17.05.2018 / 21:08
1

That way it works, when you get the name, the return is a vector.

 function limpaCampos() {
      var x = document.getElementsByName("form_txt");
      for (i = 0; i < x.length; i++) {
              x[i].value = "";
      }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputid="01" type="text" name="form_txt"/>
    <input id="01" type="text" name="form_txt"/>
    <input type="button" onclick="limpaCampos();"/>
    
17.05.2018 / 21:09