So im quite new to javascript and i tried making something simple as entering a value and add 150 to it but it wont show number + 150? Pictures below
Asked
Active
Viewed 53 times
-2
-
Dont mind the "check if your right" button, i was just messing around before i decided to make this – Philip Svenningsen Arnevig Mar 29 '18 at 23:22
2 Answers
0
Because you're actually concatenating a string with a number. The input value is a string, so before operating with it, parse it to int with parseInt
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt

Javier S
- 379
- 3
- 13
-
Thank you, i read through the link and it gave me a clearer picture :) – Philip Svenningsen Arnevig Mar 29 '18 at 23:31
0
That's because you are concatenating strings. You need to convert the strings to integers by using parseInt()
, and then add the numbers.
https://www.w3schools.com/jsref/jsref_parseint.asp
var fullprice = parseInt(price) + 150;

Gregory R.
- 1,815
- 1
- 20
- 32
-
Thank you very much, it worked! But i do wonder why it doesnt work with just price + 150 cause none of them are string or am i wrong? :) – Philip Svenningsen Arnevig Mar 29 '18 at 23:30
-
Yes, price is a string since you are using getElementById("pris").value to retrieve the value from HTML. – Gregory R. Mar 29 '18 at 23:35
-
Even thought there is no need to use types in Javascript, there are! An input can contain a number but it's value is returned as a String. `typeof "5"` would return `string` and `typeof 5` would return `number` – Javier S Mar 29 '18 at 23:37
-
Ah i see, so i would just use parseInt() to get number instead of string? :) – Philip Svenningsen Arnevig Mar 29 '18 at 23:40
-
Yes. you can always check the type of a variable by using the `typeof` operator. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof – Gregory R. Mar 29 '18 at 23:42
-