Identify inputs in a div

Asked

Viewed 140 times

1

People I would like to know if there is any way to identify inputs within a div, without using name, id or class.

Example:

<div>

      <input type='text'>

      <input type='text'>

      <input type='text>

     <button onclick='enviar(enviar-o-texto-do-primeiro-input, enviar-o-texto-do-segundo-input , enviar-o-texto-do-terceiro-input);>enviar</button>

</div>

I wish I could send input text without using id, class, name, because I’m creating the div automatically and if I put an id for each one, all the other div will have the same id in the input.

1 answer

2

You can pick it up by tag name using .getElementsByTagName() the index of the elements, starting with the 0. But first you have to catch the father div with .parentNode.

To do this, just send to the function the button itself with this:

function enviar(botao){
   var text_1 = botao.parentNode.getElementsByTagName("input")[0].value;
   var text_2 = botao.parentNode.getElementsByTagName("input")[1].value;
   var text_3 = botao.parentNode.getElementsByTagName("input")[2].value;
   console.log(text_1, text_2, text_3);
}
<div>
   <input type='text' value="A">
   <input type='text' value="B">
   <input type='text' value="C">
   <button onclick='enviar(this)'>enviar</button>
</div>

In the case of not having a defined number of inputs, another approach would be to count how many intputs a div contains and add the texts in an array:

function enviar(b){
   
   var textos = [];
   var bts = b.parentNode.getElementsByTagName("input");
   for(var botao of bts){
      textos.push(botao.value);
   }
   
   console.log(textos);
   
}
<div>
   <input type='text' value="A">
   <input type='text' value="B">
   <input type='text' value="C">
   <button onclick='enviar(this)'>enviar</button>
</div>

You will have an array of texts and can use them as you wish.

  • Thank you very much, I managed to do it the way you said. there is here some corner to put the question as solved or mark your as best answer?

  • You have to the left, below the voting arrows.

Browser other questions tagged

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