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
  • 21,497
  • 7
  • 62
  • 96
Daniel
  • 1,438
  • 6
  • 20
  • 37

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,586
  • 2
  • 33
  • 64
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,431
  • 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,822
  • 4
  • 31
  • 52
Hatem Ahmed
  • 180
  • 8