1

I am trying to add the number mathematically, but it keeps adding the number after it.

It takes the id number (begen), then it gets the number inside another div (kacbegen).

var begen = $(this).attr('id');
var kacbegen = $("#math" + begen).text();
var toplam = (kacbegen + 1);

alert(toplam);

However, when doing the math (toplam), it alerts all the numbers.How to add the number mathematically ?

user198989
  • 4,574
  • 19
  • 66
  • 95

5 Answers5

7

Convert it to number via adding a +:

var toplam = (+kacbegen + 1);

Unary plus (+)

The unary plus operator precedes its operand and evaluates to its operand but attempts to converts it into a number, if it isn't already.

Jai
  • 74,255
  • 12
  • 74
  • 103
2

It looks like you're working with Strings (and thus a + b is the concatenation operator) when you want to be working with Number (so x + y would be addition)

Perform your favorite way to cast String to Number, e.g. a unary +x

var kacbegen = +$("#math" + begen).text();
Paul S.
  • 64,864
  • 9
  • 122
  • 138
1

You need to use parseInt to convert kacbegen, which is a String instance, to a Number:

var begen = $(this).attr('id');
var kacbegen = $("#math" + begen).text();
var toplam = (parseInt(kacbegen) + 1);

alert(toplam);

The + operator, when used with a String on either side, will serve as a concatenation, calling Number.prototype.toString on 1.

James Wright
  • 3,000
  • 1
  • 18
  • 27
1

You need to cast the contents to a number:

var contents = $("#math" + begen).text();
var kacbegen = parseFloat(contents);
axelduch
  • 10,769
  • 2
  • 31
  • 50
1

You use kacbegen as a string. Please use as a integer use parseInt(kacbegen) + 1

Bhavik Jani
  • 180
  • 7