0

I want to convert the value of an element, say, an input into a number so I can add numbers. My current code only adds the number to the end:

var inputValue = document.getElementById("input").value;
  console.log(inputValue + 9);
<input id="input" value="123">

I have tried Number() but that results in NaN. How can I obtain the number value and add a number to it?

Update: I've solved my own question. Oops. Thanks everyone who helped.

LegitCoder
  • 17
  • 5

2 Answers2

3

You can do that just by using Number()

var inputValue = Number(document.getElementById("input").value);
  console.log(inputValue + 9);
<input id="input" value="123">
Ahmed Gaafer
  • 1,603
  • 9
  • 26
  • Please look at the comments on the question; if you see one that starts with "Does this answer your question?" followed by a link to another question. Navigate to that link and see if the answers there answer this question. If so, please don't answer this one, since it is a duplicate. – Heretic Monkey Jan 11 '21 at 21:01
  • @HereticMonkey thanks for the clarification will make sure to review other questions first before answering – Ahmed Gaafer Jan 11 '21 at 21:03
1

var inputValue = Number.parseFloat(document.getElementById("input").value) + 9;
console.log(inputValue);
<input id="input" value="123">

You can use Number.parseFloat or Number.parseInt.

Eduardo Coltri
  • 506
  • 3
  • 8
  • Please look at the comments on the question; if you see one that starts with "Does this answer your question?" followed by a link to another question. Navigate to that link and see if the answers there answer this question. If so, please don't answer this one, since it is a duplicate. – Heretic Monkey Jan 11 '21 at 21:00