0

I am trying to add two variables but they are concatenating with each other instead of adding

 var price = 10;
 $("#val").blur(function(){
  var get_val = $(this).val();
  var get_vale = price + get_val ;
  alert("there are " + get_vale + " in your cart");
 });

How do I add these variables and not concatenate them?

Rune FS
  • 20,997
  • 6
  • 60
  • 93
Daniel
  • 1,358
  • 5
  • 18
  • 35

3 Answers3

5

Maybe the value you are getting from $("#val") is a string instead of an int.

Use parseInt, lookup the Documentation

var price = 10;
$("#val").blur(function(){
  var val = $(this).val(),
      int_val = parseInt(val, 10), //ensure this is an Int
      get_vale = price + int_val;
 alert("there are " + get_vale + " in your cart");
});

Specified radix is 10, as written in the documentation:

Specify 10 for the decimal numeral system commonly used by humans

Community
  • 1
  • 1
steo
  • 4,485
  • 2
  • 32
  • 62
2

You are trying to concat string and number. Previously, you must to convert string to number. There is some ways to do it:

var get_val = +$(this).val();

or

var get_val = Number($(this).val());

or if you want integer

var get_val = parseInt($(this).val());

otherwise

var get_val = parseFloat($(this).val());
marsh
  • 1,401
  • 1
  • 13
  • 19
1

to concatenate variables use the "+" sign and use the parseInt function to get the numeric value of the variable in order to properly do math functions

var get_val = parseInt($(this).val());
talemyn
  • 7,422
  • 4
  • 27
  • 47
Hatem Ahmed
  • 161
  • 8