How to know the dynamically created textbox id?

Asked

Viewed 335 times

1

I got a little problem.

I need to know which id of input type='text' the user is typing, and the inputs are generated dynamically. With each new input, a new id is generated with a counter progressively increasing how much the user needs.

For example... by default there is only one field, and when it presses the button of "+"

A new field appears with ids "txtOutrosNomes1", "txtOutrosNomes2" and so on

How to get the name of this id that was typed by the user?

EDITION 1

 var divResponsible = $(document.createElement('div')).attr("id", 'respDiv' + contarEmails);
        divResponsible.after().html("<div id='contentEmails'><div class='row'> <div class='col-lg-12'><div class='col-lg-3'></div> <div class='col-xs-4 col-lg-4 col-md-4 col-sm-4'><div class='form-group has-feedback' id='divOutrosNomes"+contarEmails+"'>Nome<input type='text' onclick='pegaValues()' class='form-control' name='txtOutrosNomes["+ contarEmails +"]' id='txtOutrosNomes"+ contarEmails +"' placeholder='Fulano da Silva' autocomplete='off' automplete='off'></div></div><div class='col-xs-4 col-lg-4 col-md-4 col-sm-4'> <div class='form-group has-feedback' id='divOutrosEmails" + contarEmails+ "'>E-mail<input type='text' class='form-control' name='txtOutrosEmails[" + contarEmails + "]' id='txtOutrosEmails"+contarEmails+"' placeholder='[email protected]' autocomplete='off' automplete='off'></div><div class='col-lg-1'></div> </div></div> </div></div><div class='msgDados"+contarEmails+"'></div><div class='conteudo-select-partner"+contarEmails+"' style='display: none;'></div> </div>");
        divResponsible.appendTo("#groupEmails");
        contarEmails++;

I generate my textbox code as well... as I would add the bootstrap classes in your solution?

  • 1

    You have here the example of this code?

  • 1

    of what dynamically generates?

  • That ... because I even have a minimal example, but, I wanted to put for you very close to what you need

5 answers

1

You can generate listeners dynamically in us inputs (beyond those that already exist) and store the id last typed into a variable id_input. Whenever you want to catch the id of input that received typing, just call this variable.

var id_input;
var conta = 1;

function geraListener(){
   var el_input = document.querySelectorAll("#conteudo input[type=text]");

   for(var x=0; x<el_input.length;x++){
      el_input[x].addEventListener('input', function(){
           id_input = this.getAttribute("id"); // retorna o ID do input
           document.getElementById("valor").innerHTML = "id do input = "+id_input; // esta linha é apenas exemplo
      });
   }

}

function addInput(){
   var novo = document.createElement("input");
   novo.setAttribute("id","txtOutrosNomes"+conta);
   novo.setAttribute("type","text");
   var div = document.querySelector("#conteudo");
   div.appendChild(novo);
   conta++;
   geraListener();
}

window.onload = geraListener;
<div id="valor">
   vazio
</div>
<div id="conteudo">
<input id="txtOutrosNomes0" type="text" />
</div>
<br />
<input type="button" value="Adicionar novo input" onclick="addInput()" />

EDIT

With jQuery it would be much easier:

var id_input;
var contarEmails = 1;

$("#groupEmails").on("input","input[type=text]", function(){
   id_input = $(this).attr("id");
   $("#valor").html(id_input); // esta linha é apenas exemplo
});

function addInput(){
   
   var nova_div = "<div id='contentEmails'><div class='row'> <div class='col-lg-12'><div class='col-lg-3'></div>"
   +"<div class='col-xs-4 col-lg-4 col-md-4 col-sm-4'><div class='form-group has-feedback' id='divOutrosNomes"+contarEmails+"'>"
   +"Nome<input type='text' onclick='pegaValues()' class='form-control' name='txtOutrosNomes["+ contarEmails +"]' id='txtOutrosNomes"+ contarEmails +"' placeholder='Fulano da Silva' autocomplete='off' automplete='off'></div>"
   +"</div><div class='col-xs-4 col-lg-4 col-md-4 col-sm-4'> <div class='form-group has-feedback' id='divOutrosEmails" + contarEmails+ "'>"
   +"E-mail<input type='text' class='form-control' name='txtOutrosEmails[" + contarEmails + "]' id='txtOutrosEmails"+contarEmails+"' placeholder='[email protected]' autocomplete='off' automplete='off'>"
   +"</div><div class='col-lg-1'></div> </div></div> </div></div><div class='msgDados"+contarEmails+"'></div><div class='conteudo-select-partner"+contarEmails+"' style='display: none;'></div> </div>";
   
   $("#groupEmails").append(nova_div);
   
   contarEmails++;

}

function pegaValues(){
   // fazer alguma coisa aqui
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">

<div id="valor">
   vazio
</div>
<div id="groupEmails">
   <div id='contentEmails'><div class='row'> <div class='col-lg-12'><div class='col-lg-3'></div> <div class='col-xs-4 col-lg-4 col-md-4 col-sm-4'><div class='form-group has-feedback' id='divOutrosNomes"+contarEmails+"'>Nome<input type='text' onclick='pegaValues()' class='form-control' name='txtOutrosNomes0' id='txtOutrosNomes0' placeholder='Fulano da Silva' autocomplete='off' automplete='off'></div></div><div class='col-xs-4 col-lg-4 col-md-4 col-sm-4'> <div class='form-group has-feedback' id='divOutrosEmails0'>E-mail<input type='text' class='form-control' name='txtOutrosEmails0' id='txtOutrosEmails0' placeholder='[email protected]' autocomplete='off' automplete='off'></div><div class='col-lg-1'></div> </div></div> </div></div><div class='msgDados0'></div><div class='conteudo-select-partner0' style='display: none;'></div> </div>
</div>
<br />
<input type="button" value="Adicionar novo input" onclick="addInput()" />

  • Niiiiiiiiiice, I will try to implement this your solution, it seems exactly what I need

  • Dude, your solution is almost perfect, there’s only one thing...

  • @gabrielfalieri Take a look at the update of the answer. if you use jQuery, it is easier. Could have included the tag in the question.

1


Just create a function to grab the element id Element id.

and in the inputs add the event onClick="mostraID(this)

// Element.id representa o identificador do elemento.
function mostraID(Element) {
  console.log(Element.id);
}

$(document).ready(function() {
    var max_input      = 10; //numero máximo de inputs  permitidos
    var wrapper         = $(".input_fields_wrap");
    var add_botao      = $(".botao_add_input");
    
    var x = 1; //initlal text box count
    $(add_botao).click(function(e){
        e.preventDefault();
        if(x < max_input){
            x++;
            $(wrapper).append('<div><input type="text" name="mytext[]" id="t'+ x +'" onClick="mostraID(this)"/><a href="#" class="remove_field">Remove</a></div>');
        }
    });
    
    $(wrapper).on("click",".remove_field", function(e){ //user click on remove text
        e.preventDefault(); $(this).parent('div').remove(); x--;
    })
    
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="input_fields_wrap">
    <button class="botao_add_input">+</button>
    <div><input type="text" name="mytext[]" id="t1" onClick="mostraID(this)"></div>
</div>

  • His solution was the simplest and most direct.. I didn’t have to adapt almost anything, it worked perfectly. Thank you

0

A minimal example is to create a function and pass the object via parameter in the event KeyDown, example:

function onGetId(input){
    console.log(input.id);
}
<input type="text" id="t1" onKeyDown="onGetId(this)" />

This is a simple code by pressing the key, the code informing you the id of the object. In your case just pass this function in the creation of the object dynamically, which will work in the same way.

If example is created a second, third and so on just add the function:

<input type="text" id="t2" onKeyDown="onGetId(this)" />
<input type="text" id="t3" onKeyDown="onGetId(this)" />

A dynamic example:

var inc = 0;
function add()
{
  var di = document.createElement("div"); 
  var ip = document.createElement("input");   
  ip.id = "n" + inc;
  inc = inc + 1;
  ip.addEventListener("keydown", function(event){
     onGetId(this);
  });
  di.appendChild(ip); 
  var ips = document.getElementById("inputs");
  ips.appendChild(di);
}

function onGetId(input){
    console.log(input.id);
}
<div id="inputs">
    
</div>
<div>
  <button onclick="add()">+</button>
</div>

0

You can go through the inputs of your application and pick up the ID’s through the method attr(). staying that way:

<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<input type="text" id="ipt1">
<input type="text" id="ipt2">
<input type="text" id="ipt3">
<input type="number" id="ipt4">

<script>
    $(document).ready(function(){
        $.each($('input[type="text"]'), function(){
            alert($(this).attr("id"));
        })
    })
</script>

Notice I added one input of the kind number just to give an example that he will be ignored.

-1

One option is to listen to events in the document, that way:

document.addEventListener('keydown',function(e){
    // se o id do target contem op prefixo txtOutrosNomes
    if(e.target && e.target.id.indexOf('txtOutrosNomes') > -1 ){
       // elemento em foco
    }
 })

Events can be changed as needed.

  • I would like to know the reason for the downvote so that I can correct or change the answer.

  • The comparison with the element name index leaves you very tied, today we have several options to have access to our elements, with Jquery for example, it is much more feasible to use $('input[type="text"] that allows you to access all input type text elements, without knowing the name or id. However, it is not my vote against. ;)

  • Agree @arllondias, in this case I would also prefer jQuery, but we answer according to the specification in the question. jQuery, Angular, React, any of them would be more "easy"... and as for indexOf also relates to the AP problem, where only the suffix is changed by adding a id. And in jQuery you wouldn’t need to make one each in all elements, could use delegate with selectors only.

  • Yes, you’re right but there I only used as an example to walk through the inputs even to alert as an example.

Browser other questions tagged

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