How to know the dynamically created textbox id?

1

I have a problem.

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

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

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

How do I 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 so ... how would you add bootstrap classes to your solution?

    
asked by anonymous 14.12.2017 / 14:36

5 answers

1

Just create a function to get 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><divclass="input_fields_wrap">
    <button class="botao_add_input">+</button>
    <div><input type="text" name="mytext[]" id="t1" onClick="mostraID(this)"></div>
</div>
    
14.12.2017 / 17:28
1

You can generate listeners dynamically in the inputs (in addition to the ones that already exist) and store the id of the last one that was typed in a id_input variable. Whenever you want to get the id of input you typed, 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 a lot 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><linkrel="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()" />
    
14.12.2017 / 15:56
0

You can go through the inputs of your application and get the ID's through the attr() method. getting it this way:

<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script><inputtype="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>

Note that I have added a input of type number just to give an example that it will be ignored.

    
14.12.2017 / 14:56
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 when you press the key, the code will inform you the id of the object. In your case it is only to pass this function in the creation of the object dynamically, which will works the same way.

If an 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>
    
14.12.2017 / 14:47
-1

One option is to listen for events in the document, like this:

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.

    
14.12.2017 / 14:52