math.random()
k so i have the code which u can check in the codepen
https://codepen.io/-bloop-/pen/bGxRpmw
in the code.. it is supposed to generate number between given min and max value
but it doesn't work properly
when i put literal numbers insted of the variable in the highlighted area in the screenshot it works
like, if i have max = 10; min = 5; as given, and in the highlighted arean insted of minValueJS i out the min value 5 directly it works.. Anyone know why??
thanks!!
10 Replies
here's the code incase u wanna see from here
Problem seems to be the type of the variable. When you access it with
getElementById
and then get the value
, that's a string. You need to cast it (convert it) to a number type first
I guess this is personal preference but... maybe consider using less spaces between each line of codewhat if I try getting with querySelector
ya sure tnx
and how would I convert it
It would be the same, as that is just a selector. The issue is with the data type. To convert to a number, use
parseInt
on the value you extract from the element.parseInt() - JavaScript | MDN
The parseInt() function parses a string argument and returns an integer of the specified radix (the base in mathematical numeral systems).
ok I'll try that and let u know tnx ❤️
number inputs also have
.valueAsNumber
property for that very reason
if in doubt with an API check MDN:
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/number#technical_summary- HTML: HyperText Markup Language | MDN
elements of type number are used to let the user enter a number. They include built-in validation to reject non-numerical entries.
Didn't know about that one, thanks! Although after a quick test it seems that it doesn't work quite as expected when used alongside a text input for example. I would still prefer to be explicit and use parseInt for that.
yep it's exclusive to
<input type="number">
, so it's indeed kinda limited.
parseInt
, parseFloat
and Number()
to the rescue then 😄he was ryt
using parseInt worked