m1xolyd1an
m1xolyd1an

Reputation: 535

Javascript, points get appended instead of added to the score field?

I looked up others with the same issue and seems like the problem is that you need to parse to an integer. I tried that but it's still appending the points instead of adding it to the score. I must be doing the pareseInt wrong but I'm not sure what...

Here's a snippet of my code

var gameButton = function(){
var userVariable = (document.getElementById("userInput").value);
var gameSecret = Math.floor(Math.random() * 100 +1);
var points = userVariable * 3.14;
var score = 0;

//check if valid entry
if(userVariable <2) {
alert("You must choose a number between 2 - 100");
} else {

//check game result
if(gameSecret>userVariable){
document.getElementById('gameSecret').innerHTML ="You won! Game Secret was " +gameSecret;
document.getElementById('points').innerHTML ="You won " +points +" points!";

//I'm pretty certain these next few lines is where I messed up
var points2 = parseInt(points, 10);
var score2 = parseInt(score, 10);
document.getElementById('score').innerHTML += score2+points2;
} else {

Upvotes: 0

Views: 102

Answers (1)

nbrooks
nbrooks

Reputation: 18233

The + operator is left-right associative, so the concatenation is trumping the addition. Also, you'll have to get the existing value of the field as a number in order to add to it:

var score = document.getElementById('score').innerHTML;
...
var score2 = parseInt(score, 10);
document.getElementById('score').innerHTML = score2 + points2;

Upvotes: 1

Related Questions