Add dynamic id with Javascript

Asked

Viewed 1,727 times

0

Appeared the need for me to create a view I need to add inputs through a button, where the user will enter the name of the field he wants to add, this name will appear in a label on top of the input, and the id of this input also has to be created dynamically, example (id="item1", id="item2")

Follow an HTML code with jQuery that is adding input already, I’m just not able to add the label with the name that the user typed in the main input and generate the id dynamically to be sent to PHP.

$(function () {
    var scntDiv = $('#dynamicDiv');
    $(document).on('click', '#addInput', function () {
              $('<p>'+
                  '<label>Nome dinamico</label>' +
          '<input type="text" id="inputeste" size="20" value="" placeholder="" /> '+
          '<a class="btn btn-danger" href="javascript:void(0)" id="remInput">'+
        '<span class="glyphicon glyphicon-minus" aria-hidden="true"></span> '+
        'Remover Campo'+
          '</a>'+
    '</p>').appendTo(scntDiv);
        return false;
    });
    $(document).on('click', '#remInput', function () {
          $(this).parents('p').remove();
        return false;
    });
});
<!DOCTYPE html>
<html lang="pt-BR">
	<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width, initial-scale=1"/>
		<title>Adicionando Campo Dinâmico</title>
		<script src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
		<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
		<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
	</head>
	<body>
		<div class="container">
			<a class="btn btn-primary" href="javascript:void(0)" id="addInput">
				<span class="glyphicon glyphicon-plus" aria-hidden="true"></span>
				Adicionar Campo
			</a>
			<br/>
			<div id="dynamicDiv">
				<p>
			        <input type="text" id="inputeste" size="20" value="" placeholder="" />
			        <a class="btn btn-danger" href="javascript:void(0)" id="remInput">
			        	<span class="glyphicon glyphicon-minus" aria-hidden="true"></span>
			        	Remover Campo
					</a>
		        </p>
		    </div>
       </div>
	</body>
</html>

  • You can use the window.prompt to capture the name of label (since in your HTML there is no field for this function); and you can use $("#dynamicDiv > p").length to capture the current number of elements and name the attribute id

1 answer

1


Just grab the input text with $("#inputeste").val() to put in the label concatenating the string to be inserted.

To generate the ids in order, I suggest a separate function for this, so that it can be called when you enter or remove items. The function will go through all inputs (except the first one) and put ids in order: item1, item2 etc..

$(function () {
   
   var scntDiv = $('#dynamicDiv');

   // função que organiza as ids
   function ids(){
      scntDiv.find("input:not(:first)").each(function(i){
         this.id = "item"+ parseInt(i+1);
      });
   }
   
   
   $(document).on('click', '#addInput', function () {
   
      var nome = $("#inputeste").val();
   
      $('<p>'+
      '<label>'+nome+'</label>' +
      '<input type="text" size="20" value="" placeholder="" /> '+
      '<a class="btn btn-danger" href="javascript:void(0)" id="remInput">'+
      '<span class="glyphicon glyphicon-minus" aria-hidden="true"></span> '+
      'Remover Campo'+
      '</a>'+
      '</p>').appendTo(scntDiv);
      
      ids();
      
      return false;
   });

   $(document).on('click', '#remInput', function () {
      $(this).parents('p').remove();
      ids();
      return false;
   });
});
<!DOCTYPE html>
<html lang="pt-BR">
	<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width, initial-scale=1"/>
		<title>Adicionando Campo Dinâmico</title>
		<script src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
		<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
		<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
	</head>
	<body>
		<div class="container">
			<a class="btn btn-primary" href="javascript:void(0)" id="addInput">
				<span class="glyphicon glyphicon-plus" aria-hidden="true"></span>
				Adicionar Campo
			</a>
			<br/>
			<div id="dynamicDiv">
				<p>
			        <input type="text" id="inputeste" size="20" value="" placeholder="" />
			        <a class="btn btn-danger" href="javascript:void(0)" id="remInput">
			        	<span class="glyphicon glyphicon-minus" aria-hidden="true"></span>
			        	Remover Campo
					</a>
		        </p>
		    </div>
       </div>
	</body>
</html>

  • It worked here! Thank you very much

Browser other questions tagged

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