Perform calculation Quantity x Value between inputs in shopping cart

Asked

Viewed 704 times

0

I’m trying to make a calculation in my shopping cart, for example: quantity x price playing the result in another input, I was able to do for the first product, but the others are 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 }  ?>&nbsp; x &nbsp;
		   <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 for calculating 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 believe that because I am searching for the id and since id is unique the calculation only occurs in the first instance of the element. There may be a simpler and more functional way, but as I said, I couldn’t solve.

1 answer

1


Yes, the ID must be unique. You can use the attribute name to identify the fields. For example like:

<div class="qty">
  <input type="text" name="quantidade" maxlength="3" />`
</div>

To get all quantity values, you can do this by using jQuery:

$('.qty').each(function () {
  var qtd = $(this).find('input[name=quantidade]').val();
  var val = $(this).find('input[name=valor_unitario]').val();
  var total = parseFloat(qtd) * parseFloat(val);
  console.log(total);
});

I made a complete example here, you can see here: https://jsfiddle.net/ghzjf58w/

Of course you need to put the tags on php, validate if the fields are filled, etc, but this should help you.

  • Hello @Ricardo Punctual, good afternoon, I already appreciate the help, how can I calculate when leaving the field?

  • 1

    @adventistapr uses onFocus in Jquery $(). Blur(leaving the field) and has the $(). Focus (entering the field) as a curiosity.

  • 1

    You mean when leaving the field "value_unitario"?

  • That’s right @Ricardopunctual.

  • 1

    It would be this: $('input[name=valor_unitario]').blur(function() { suaFuncaoQueCalcula(); });

Browser other questions tagged

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