I'm trying to use .focus () after adding more input fields with jQuery, but it only works with the input field already present in HTML and not with the ones added.
- For example, if I click on the input field that is in the form, an alert will appear, but if I add more input fields and click on them, nothing will appear.
Is there a solution? Thanks! :)
$(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" );
});
$('form :input').focus(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>