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>
3

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

innerText does not work in Firefox, use innerHTML or textContent (the latter not supp. by IE < 9) if you want to be w3c-DOM compliant.
@deamentiaemundi, i have changed that. :)
Than let me be a dutiful member of this community and give you a thumbs-up, no wait, wrong group, ah it's a +1, sorry.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.