How to return the number of the input position within a form?

Asked

Viewed 762 times

0

I would like to know how to recover the input position with javascript, when it is clicked.

When I click on the first input, it would return the value to me 0; In the second input, the value 1, and so on. The ultimate goal is to be able to execute the code within the if, but only when the input list matches only the user-selected/clicked input.

Follow the code so you can see how I’m doing.

var descendentes = document.querySelectorAll(".form-edit input");
//alert(descendentes.length); //Aqui ele retorna a quantidade de inputs que tenho, que são 3.
for(var i = 0; i < descendentes.length; i++){
  descendentes[i].addEventListener("click", function (e){
    //alert("Ok!"); 
    
    for(var i = 0; i < descendentes.length; i++){
      var clicado = document.forms[0].elements[i]; //É neta linha que tento retornar o número, mas ele me retorna outra coisa(Ele informa que é um objeto html)
      alert(clicado); //No caso aqui, exibiria o número do input clicado
      /*if(clicado == i){
        alert("Funcinou!");
      }*/ //O if, neste caso, caso eu clicar no input que eu desejo, eu entro numa seção de códigos para serem executados.
    }
  })
}
<form class="form-edit">
  <div id="teste">
    Nome: <input type="text" name="name" /><br />
    Idade: <input type="text" name="age" /><br />
    E-mail: <input type="text" name="email" /><br />
    Lore: <select>
      <option>Lorem</option>
      <option>Ipsum</option>
      <option>Dolor </option>
    </select>
  </div>
</form>

3 answers

3

Your nested loops are redefining the value of i and creating confusion. The correct thing in this case would be to create a closure that captures the current value of the most external loop, so you don’t need to do another:

var descendentes = document.querySelectorAll(".form-edit input");
//alert(descendentes.length); //Aqui ele retorna a quantidade de inputs que tenho, que são 3.
for(var i = 0; i < descendentes.length; i++){
  descendentes[i].addEventListener("click", criaListener(i));
}

function criaListener(i) {
    return function() {
        alert(i);
    }
}
<form class="form-edit">
  <div id="teste">
    Nome: <input type="text" name="name" /><br />
    Idade: <input type="text" name="age" /><br />
    E-mail: <input type="text" name="email" /><br />
    Lore: <select>
      <option>Lorem</option>
      <option>Ipsum</option>
      <option>Dolor </option>
    </select>
  </div>
</form>

If you prefer, you can use a immediately executed function instead of creating the criaListener:

descendentes[i].addEventListener("click", (function(iAtual){
    return function() {
        alert(iAtual);
    }
}(i)));

2


You followed the right path but missed one small detail:

document.forms[0].elements[i]

will return the element html. The correct index is itself i.

  descendentes[i].addEventListener("click", function (e){
    for(var i = 0; i < descendentes.length; i++){
      var clicado = document.forms[0].elements[i]; // esse é o ELEMENTO clicado e não o índice
        if(clicado == this) { // elemento no índice i é igual ao elemento que foi clicado?
            alert(i); // sim! então o indice desse input é i
            break;
        }

    }
  });
  • The other comments above are perfect too, but what I understood was your! Thanks for the help

2

You can do so by looking for the parent element and choosing the child inputs. You can be more generalist or even use el.parentNode.children. But if in the code you go through all the elements to add to them the Event Handler, then the idea of the bfavaretto is the best.

var descendentes = document.querySelectorAll(".form-edit input");
//alert(descendentes.length); //Aqui ele retorna a quantidade de inputs que tenho, que são 3.
for(var i = 0; i < descendentes.length; i++){
  descendentes[i].addEventListener("click", getIndex);
}

function getIndex(){
    var el = this;
    var siblings = [].slice.call(el.parentNode.querySelectorAll('input'));
    var index = siblings.indexOf(el);
    alert(index);
    return index;
}
<form class="form-edit">
  <div id="teste">
    Nome: <input type="text" name="name" /><br />
    Idade: <input type="text" name="age" /><br />
    E-mail: <input type="text" name="email" /><br />
    Lore: <select>
      <option>Lorem</option>
      <option>Ipsum</option>
      <option>Dolor </option>
    </select>
  </div>
</form>

Browser other questions tagged

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