0

I have an issue with the variables + They both result me 310. But they both have to result me 13 because var1 = 3 and var2 = 10.

var var1 = document.getElementById("start").value;
var var2 = 10;
var3 = var1 + var2; 
alert(var3);

And Its Html:

<input type="text" id="start" value="3" />
1
  • Its HTML is : <input type="text" id="start" value="3" /> Commented Aug 29, 2016 at 6:18

4 Answers 4

1

just use parseInt() for the value you get from textbox

var var1 = document.getElementById("start").value;
var var2 = 10;
var3 = parseInt(var1) + var2; 
alert(var3);

Working Demo

Sign up to request clarification or add additional context in comments.

1 Comment

A second faster. Haha. I have the same answer jsfiddle.net/xkgb45b6 Great answer!
0

They have become strings. Convert to number

var var3 = Number(var1) + Number(var2); 

1 Comment

Sorry. What is the issue for scroll bottom? Could u please elaborate?
0

your trying to add two strings together. use the following to change them to numbers.

var var3  =  +var1 + +var2

Comments

0

The main problem is this part,

document.getElementById("start").value

becaus it returns a string, as all input values are strings in HTML.

For using this value as a number, you could use various methods to convert a string to a number, like

  • parseInt(string, base), result is a integer number
  • parseFloat(string), result is a floating number
  • Number(string), using the number object
  • +string, implicit casting to number with an unary plus symbol.
  • and some others, like the minus symbol with calculation, like string1 - string2 yields to number - number.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.