protik protik - 6 months ago 181
jQuery Question

Calculate price and quantity using jquery or javascript

How to calculate price and quantity. I don't want to remove currency type. The price is php generated so i just want to show a calculated price when update quantity using jquery or javascript. Thank you.

Here is working demo :



$('input[name=\'quantity\']').on('change keyup click', function() {
var price = $('.price').text().substr(1);
var quantity = $('.quantity').val();

$('.total').text(price * quantity);

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Total : <span class="total">$50.00</span></br>
Price : <span class="price">$50.00</span></br>
<input name="quantity" class="quantity" value="1" />




Answer

You can get the currency with a substring function:

var currency = $('.price').text().substr(0, 1);

...and then add it to the text function:

$('.total').text(currency + (price * quantity).toFixed(2)); // Adds $ and .00 decimals

Full code:

$('input[name=\'quantity\']').on('change keyup click', function() {
  var price = $('.price').text().substr(1);
  var currency = $('.price').text().substr(0, 1);
  var quantity = $('.quantity').val();

  $('.total').text(currency + (price * quantity).toFixed(2));

});