Reputation: 623
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.
Upvotes: 2
Views: 115
Reputation: 634
You are concatinating strings, so you have to convert them to numbers first
var amount = +price + +qty;
Upvotes: 2
Reputation: 2881
var amount = parseFloat(price).toFixed(2) + parseInt(qty, 10);
Upvotes: 1
Reputation: 30648
price and qty is a string parse it to float or any numeric type
var amount = parseFloat(price) + parseFloat(qty);
Upvotes: 1
Reputation: 87073
var amount = parseInt(price, 10) + parseInt(qty, 10);
or
var amount = parseFloat(price).toFixed(2) + parseInt(qty, 10);
Because, .val()
returns string property and +
has dual roll of adding and concatenation of string. Which depends on type of variables.
If parseFloat()
or parseInt()
depends on you, how you want your output.
Upvotes: 2
Reputation: 145398
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);
Upvotes: 4