-2

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" />
j08691
  • 204,283
  • 31
  • 260
  • 272
protik
  • 59
  • 1
  • 9

1 Answers1

3

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));

});
jehna1
  • 3,110
  • 1
  • 19
  • 29
  • I don't want to add that manually. That is php generated and i have other currencies so Any other way?? – protik May 24 '16 at 20:38
  • @protik changed my answer to automatically fetch the currency from the `.price` span. Would that work? – jehna1 May 24 '16 at 20:42