I'm creating a sales screen, where I have a form with 4 fields:
- PRODUCT
- QUANTITY
- PRICE
- TOTAL
The number of times these fields will repeat will depend on the need to add more items. Using JS I can make fields dynamically added by clicking a Button using the append () method.
But I need to calculate the QUANTITY and PRICE fields to generate the TOTAL, I was only able to make the first item calculated, I would like to know how to do it so that the other fields added later also calculate.
$(document).ready(function() {
$("#novoProd").click(function() {
var novoItem = $("#item").clone().removeAttr('id');
novoItem.children('input').val('');
$("#formulario").append(novoItem);
});
});
function calcular(){
var valor1 = parseInt(document.getElementById('txt1').value);
var valor2 = parseInt(document.getElementById('txt2').value);
document.getElementById('result').value = valor1 * valor2;
}
input[type="number"] {
width: 50px;
}
label {
font-weight: bold;
margin-left: 10px;
}
div.item {
border: 1px solid black;
padding: 10px;
margin: 5px;
}
<html>
<head>
<title>teste</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><linkrel="stylesheet" href="style.css">
</head>
<body>
<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 name="produtoId[]">
<option value="1">Produto 1</option>
<option value="2">Produto 2</option>
<option value="3">Produto 3</option>
<option value="4">Produto 4</option>
<option value="5">Produto 5</option>
</select>
<label>Quantidade:</label>
<input id="txt1" type="number" name="quant[]"/>
<label>Preco:</label>
<input id="txt2" type="number" name="preco[]"/>
<label>Total:</label>
<input id="result" type="text" onclick="calcular()"/>
</div>
</form>
</body>
</html>