-1

I am attempting to make a button that when clicked outputs an integer from 1-11. I have tested the "getRandomInt" function and it works, however when I try to add the button aspect nothing comes up when I click the button. Also the console does not log any errors. code:

<form>
<input type="button" onclick="getRandomInt()" value="Click Here">
<br>
</form>
<script type="text/javascript">

function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
};
document.write(getRandomInt(1, 12));

</script>

Can someone explain it in layman's terms how to fix this because the function should be correct, I think the button is wrong somehow and I think the two aren't being connected properly.

2 Answers2

2

You need to supply arguments to getRandomInt when you call it. You also need to wrap the function call in something like document.write so you can see the output

<form>
    <input type="button" onclick="document.write(getRandomInt(1, 10))" value="Click Here">
    <br>
</form>
<script type="text/javascript">

function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min)) + min;
};
document.write(getRandomInt(1, 12));

</script>
J Delaney
  • 589
  • 4
  • 17
0

You are missing the glue between your program logic (getRandomInt()) and the presentation (document.write()), i. e. later statement is not part of your button's event handler.

I'd like to propose the following solution which avoids calling document.write and instead sets the text property of a dedicated <span id='display-random'>:

function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min)) + min;
}

var button = document.getElementById('button-random'),
    display = document.getElementById('display-random');

button.addEventListener('click', function(event) {
  display.textContent = getRandomInt(1, 12);
});
<form>
  <input type="button" id="button-random" value="Click Here">
</form>
<span id="display-random"></span>
Community
  • 1
  • 1
le_m
  • 19,302
  • 9
  • 64
  • 74