In HTML I have a basic form:
let numero = 1;
let nuevo = function() {
numero++;
jQuery('.inputs').append(`<section id="${numero}"><input type="text" name="codigo" placeholder="Ingrese Codigo"><input type="text" name="namearti" placeholder="Ingrese Nombre"><input type="text" name="cantidad" placeholder="Ingrese Cantidad"> <button class="btn-danger" onclick="eliminar(${numero})">Eliminar</button></section>`);
}
let eliminar = function(n) {
jQuery("section").remove(`#${n}`);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<form method="post" action="gestionArticulos.php">
<div class="inputs">
<input type="text" name="codigo" placeholder="Ingrese Codigo">
<input type="text" name="namearti" placeholder="Ingrese Nombre Articulo">
<input type="text" name="cantidad" placeholder="Ingrese Cantidad">
<button type="button" onclick="nuevo();">Agregar</button>
</div>
<input type="submit" name="enviar">
</form>
When I refer to code optimization, it is that if at some point I have to modify the HTML to insert 10 fields to the form, I don't have to reinsert those 10 fields inside the jQuery, but find a more comfortable and dynamic way, so that I don't have than "reinsert" the same HTML inside a jQuery append.
If what you want is to copy the fields from
.inputs
without having to repeat them in the JavaScript code, what you can do is duplicate the code from.inputs
and add it to asection
behind.inputs
(although the code you were adding is not the same because the button is not is Add but Remove and you would have to change its functionality). Something like this (commented out):As you can see, this solution doesn't rely on generated IDs or global variables to know which section to remove. You can use the jQuery method
.closest
that will return the closest ancestor that meets a condition. So when you click on the Delete button, you would only have to search for a.closest("section")
to find the section that contains the fields to be deleted:With those changes, you can see it working here: