I'm trying to make a calculation in my shopping cart, for example: quantity x price throwing the result in another input, I could do for the first product, but in the others it is not working.
The script I have in php is this:
<form class="container">
<div class="cartContent clearfix" method="post" action="#">
<div id="cartContent">
<div class="item">
<div class="cart_img"><img src="<?php echo "../".$list['caminho_thumbs']; ?>" alt="" width="60" /></div>
<a href="" class="product_name">
<span><?php echo $list['nome']; ?></span>
<small><strong>CÓDIGO: <?php echo $list['codigo_iabv']; ?></strong></small>
</a>
<a href="orcamentos.php?del=<?php echo (int)$id; ?>" class="remove_item"><i class="fa fa-times"></i></a>
<div class="qty">
<input type="text" value="1" name="total" maxlength="3" id="total" />
</span></div>
<div class="qty">
<?php if ( isset($_SESSION["quantidade"][$id]) && ($_SESSION["quantidade"][$id] != 0) ){ ?>
<input type="text" id="quantidade" name="quantidade" maxlength="3" value="<?php echo $_SESSION["quantidade"][$id] ?>" id_qtd="<?php echo $list['id_produto'] ?>" />
<?php } else { ?>
<input type="text" id="quantidade" name="quantidade" value="<?php echo $QTD; ?>" class="input" id_qtd="<?php echo $list['id_produto']; ?>" />
<?php } ?> x
<input type="text" value="1" name="valor_unitario" id="valor_unitario" />
</div>
<div class="clearfix"></div>
</div>
<div class="clearfix"></div>
</div>
</div>
</form>
The script I have to do the calculation is this:
function id(el) { return document.getElementById(el); } function total(un, quantidade) { return parseFloat(un.replace(',', '.'), 10) * parseFloat(quantidade.replace(',', '.'), 10); } window.onload = function() { id('valor_unitario').addEventListener('keyup', function() { var result = total(this.value, id('quantidade').value); id('total').value = String(result.toFixed(2)).formatMoney(); }); id('quantidade').addEventListener('keyup', function() { var result = total(id('valor_unitario').value, this.value); id('total').value = String(result.toFixed(2)).formatMoney(); }); } String.prototype.formatMoney = function() { var v = this; if (v.indexOf('.') === -1) { v = v.replace(/([\d]+)/, "$1,00"); } v = v.replace(/([\d]+)\.([\d]{1})$/, "$1,$20"); v = v.replace(/([\d]+)\.([\d]{2})$/, "$1,$2"); v = v.replace(/([\d]+)([\d]{3}),([\d]{2})$/, "$1.$2,$3"); return v; };
I think that because I'm looking for the id and id is unique, the calculation only occurs in the first instance of the element. It may be that there is a simpler and more functional way, but as I said, I could not solve it.