Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery addition error

Tags:

jquery

I have a strange error going on. This is the jQuery function

jQuery(document).ready(function(){
  jQuery("#new_customer").delegate(".kool", "keyup", function(event) {  
    var SelectProd = jQuery('.price, .qty',this);
    var price = jQuery('.price', this).val();
    var qty =   jQuery ('.qty', this).val();
    var amount = price + qty;
    var lineItemWrapperElement = SelectProd.parent().parent();
    jQuery("input.amount", lineItemWrapperElement).val(amount);
  });
 });

Instead of doing addtion "+" is concatinating. i.e 12+1 is coming as 121 what seems to be the problem?? any guidance would do.

like image 454
bharath Avatar asked Sep 18 '26 07:09

bharath


1 Answers

This happens because you concatenate strings. You have to convert variables to numeric type. I assume your price can be a float, so you can use parseFloat() function:

var amount = parseFloat(price) + parseFloat(qty);

In order to fix the precision you can also use toFixed() after:

amount = amount.toFixed(2);
like image 56
VisioN Avatar answered Sep 20 '26 21:09

VisioN



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!