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 attributeid
– Valdeir Psr