1

All I'm trying to do is have the user click a button to generate a random number. It seems to work, but the number only displays for a second before disappearing. Here is my code.

<!DOCTYPE html>

<head>
</head>

<body>

<h3>
This is a random number generator!
</h3>

<form onsubmit= "randomNumber()">
<input type="submit" value="Click me!">
</form>

<script>
function randomNumber() {
    document.write(Math.floor(Math.random() * 10));
}
</script>

<p id="number">
</p>
</body>
</html>
Lou
  • 47
  • 1
  • 5
  • 2
    You need to prevent the form from submitting, and [you should not use `document.write`](http://stackoverflow.com/q/802854/1048572), as it purges the current page. – Bergi Oct 26 '15 at 23:07
  • 1
    Do not use document.write http://stackoverflow.com/questions/802854/why-is-document-write-considered-a-bad-practice – epascarello Oct 26 '15 at 23:07
  • @epascarello: 1s too late :-D – Bergi Oct 26 '15 at 23:09

2 Answers2

4

You need

<form onsubmit="randomNumber(); return false;">

to prevent a new load of the page and

function randomNumber() {
    document.getElementById('number').innerHTML = Math.floor(Math.random() * 10);
}

to set the value.

Nina Scholz
  • 323,592
  • 20
  • 270
  • 324
1

Nina's answer is good, but you don't really need a form for that. How about this instead of your form?

<button onclick="randomNumber()">Click me!</button>

Then the randomNumber function would go as Nina suggested:

function randomNumber() {
    document.getElementById('number').innerText = Math.floor(Math.random() * 10);
}

Since there is no form, there's no need to prevent the form from actually being sent.

Incidentally, this would put the random number in the p with id "number", which I guess is what you wanted. However, if you want to leave a page which contains just the number, use document.write instead of document.getElementById..., as in your original snippet.

unpollito
  • 787
  • 1
  • 9
  • 26