Change this...
$('form :input').focus(function() {
To this...
$(document).on('focus', 'form :input', function() {
This will cause all future-created elements to retain that binding. These are called Delegated Event Handlers. The jQuery POD explains both the problem and the solution...
Event handlers are bound only to the currently selected elements; they must exist at the time your code makes the call to .on(). To ensure the elements are present and can be selected, place scripts after the elements in the HTML markup or perform event binding inside a document ready handler. Alternatively, use delegated event handlers to attach event handlers....
The document element is available in the head of the document before loading any other HTML, so it is safe to attach events there without waiting for the document to be ready. (Source: jQuery on
Handler Documentation.)
Full working demo with your code sample...
$(document).ready(function(){
var cont = 1;
$( "#add-campo" ).click(function() {
cont++;
$( '<div class="form-group" id="campo'+cont+'"> <label>Campo: </label> <input type="text" name="titulo[]" placeholder="Digite aqui"> <button id="'+cont+'" class="btn-apagar"> - </button> </div>' ).appendTo( "#formulario" );
});
$(document).on('focus', 'form :input', function() {
alert( "Handler for .focus() called." );
});
$( "form" ).on( "click", ".btn-apagar", function() {
var button_id = $( this ).attr("id");
$( '#campo' +button_id+'' ).remove();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>ADICIONAR CAMPOS</h1>
<form id="add-pub" method="POST">
<div id="formulario">
<div class="form-group">
<label>campo: </label>
<input type="text" name="titulo[]" placeholder="Digite aqui">
<button type="button" id="add-campo"> + </button>
</div>
</div>
<div class="form-group">
<input type="button" name="PubRot" id="PubRot" value="PUBLICAR">
</div>
</form>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…