简体   繁体   中英

How to set a value of input field as a parameter of function?

I tried to use input as a parameter of a function. The problem is that when I use numbers as parameters (for example: getRandomNumber(1,20)) all works right. But when I'm using the approach represented below and type min = 2 and max = 5 I'm getting numbers 0,1,2,3. How to force it works like getRandomNumber(1,20)?

I guess mistake in the Math.floor(Math.random()*(max-min+1)+min)

 <html> <head> </head> <body> <input type = "button" value = "Get random number" onclick = "getRandomNumber(document.getElementById('min').value,document.getElementById('max').value)"> <input type = "input" id = "min" placeholder = "min"> <input type = "input" id = "max" placeholder = "max"> <script> var p = document.createElement("p"); document.body.appendChild(p); function getRandomNumber(min,max) { p.innerHTML = Math.floor(Math.random()*(max-min+1)+min); } </script> </body> </html> 

It should be like below:

Math.floor(Math.random() * (max - min + 1)) + min

and also convert the inputs to number for example use document.getElementById('min').valueAsNumber

Actually document.getElementById giving you a string value but you need a int value thatswhy its not working.

You just need to recive the value in function and then do the process min=value.parseInt()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM