11
I implemented a script that dynamically adds fields to a form, in this case a form to add products and their amount.
The code is here: http://jsfiddle.net/3Lzcn7dc/
I find this code very bureaucratic, because every time the "New product" button is triggered, it is necessary to do:
- Clone the div item
- Change the id of the div and the fields productId and Quant
- Use a counter to increment ids and Names to ensure they are not equal
- Use an Hidden attribute (itemCont) to pass to the server the amount of new products that have been created, to know how many times I will have to call $_POST["productoId__"], as there may be hundreds of products created.
I would like the opinion of colleagues to perfect this code, making it leaner. Below follows 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);
});
});
I recently had the same need and arrived at the same solution: Using the clone. I don’t think the code is bureaucratic. Obs: The difference is that it used ASP.net MVC
– Everson Moura