I've implemented a script that dynamically adds fields to a form, in this case a form to add products and their quantity.
The code is here: link
I am finding this code very bureaucratic, because every time the button "NewProduct" is triggered, it is necessary to do:
I would like the opinion of colleagues to improve this code, making it leaner. Here is the code:
HTML:
<form action="cadastro.php" method="post" id="formulario">
<input type="button" id="novoProd" value="Novo produto"/>
<input type="submit" value="enviar"/>
<div id="item" class="item">
<label>Selecione o produto:</label>
<select id="produtoId" name="produtoId">
<option value="1">Produto 1</option>
<option value="5">Produto 2</option>
<option value="9">Produto 3</option>
</select>
<label>Quantidade: </label>
<input type="number" id="quant" name="quant"/>
</div>
<input type="hidden" id="itemCont" value="1"/>
</form>
JAVASCRIPT:
$(document).ready(function(){
var itemCont = 1;
$("#novoProd").click(function(){
var novoItem = $("#item").clone();
// modifica o id do item recem criado
$(novoItem).attr("id","item"+itemCont);
var novoSelect = $(novoItem).children()[1];
$(novoSelect).attr("id","produtoId"+itemCont);
$(novoSelect).attr("name","produtoId"+itemCont);
var novoSelect = $(novoItem).children()[3];
$(novoSelect).attr("id","quant"+itemCont);
$(novoSelect).attr("name","quant"+itemCont);
$("#formulario").append(novoItem);
itemCont++;
$("#itemCont").val(itemCont);
});
});