Generating random Numbers through input text

Generating random Numbers through input text
0

#1

I have this as my generate random number function:

function getRandomNumber(min, max) {
				
				var x = document.getElementById("ok");
				
				for(var i = 0; i < 10; i++) {
					var c = Math.floor(Math.random() * (max - min + 1)) + min;
					x.innerHTML += " " + c;
					
				}
}

and in my html i have my input types:

<input type="text" id="num1" name="one"/  >
<input type="text" id="num2" name="two"/  >
<button onclick="getRandomNumber(document.getElementById('num1').value,document.getElementById('num2').value);">Generate 50 random numbers
</button >
		<p id="ok"></p>

If i use getRandomNumber(5, 10);, the code works as intended and generates numbers through 5-10, but if i use the document.getElementById(‘num1’).value and the other one, the code doesn’t work.

I did console.log tests and it does print the correct value of the inputs… I don’t know why.

The incorrect output show like:


Thanks


#2

Just a fyi, The ‘//’ in the code are only there so i can post it, otherwise it wouldnt show for some reason. There are no syntax errors in the console.log report


#3

Hi xtnd,

First of all, try reversing the quotation marks in the button element to this effect:

onclick='getRandomNumber(document.getElementById("num1").value,document.getElementById("num2").value);'

Also, I think you have to either change the input types to number or use parseInt() to make sure that all values in your function are numbers and not strings.


#4

I’ve edited your post for readability. When you enter a code block into the forum, precede it with a line of three backticks and follow it with a line of three backticks to make easier to read. See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.


#5

As @pwkrz suggested, you need to convert the values of the two inputs to numbers, because they are just strings via the .value reference.

Also, strongly consider removing the onclick event handler from your html and using the addEventListener function handling the click event. See below for how this could be done:

document.querySelector("button").addEventListener("click", function() {
  getRandomNumber(parseInt(num1.value), parseInt(num2.value));
});

#6

Thanks for the reply, the parseInt addition seemed to work. I’m not sure why to be honest but i’ve been trying to figure this out for hours :grimacing:


#7

Oh, i understand now. thats why my min value was always at the end of the number because it thought i was concatenating a string instead of doing a math formula.