How to calculate two dynamically generated fields by the append() method?

Asked

Viewed 58 times

1

I’m creating a sales screen, where I have a form with 4 fields:

  • PRODUCT
  • AMOUNT
  • PRICE
  • TOTAL

The amount of times these fields will repeat will depend on the need to add more items. Using JS I can get the fields to be added dynamically by clicking on a Button, using the append method().

However I need to calculate the fields QUANTITY and PRICE to generate the TOTAL, I could only make the first item to be calculated, I would like to know how to make the other fields added later also perform the calculation.

$(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>
<link rel="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>

  • What you want and add various products, their unit value and the total be automatically be calculated, correct?

  • that’s right, because in the example I put only the first item is being calculated

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.