1

This code should generate a page that displays a random number. Why doesn't it work?

<html>
    <head>
        <script type="text/javascript">
            window.onload = generateRandomNumber();
function generateRandomNumber()
{
    var n = 25;
    var number = Math.floor(Math.random()*n)+1;
    document.getElementById("randomNumber").value = number;
}
</script>
    </head>
    <body>
        <h1>
            Random number generated = <h1 id="randomNumber"></h1>
        </h1>
    </body>
</html>
2
  • check my answer.. updated as per your updated question. Commented Jan 11, 2012 at 10:49
  • uploaded snapshot for your reference.. check it out Commented Jan 11, 2012 at 11:37

2 Answers 2

8

Make use of window.onload. try this

<head>
     <script type="text/javascript">
        window.onload = function(){
             var n = 25;
             var number = Math.floor(Math.random()*n)+1;
             document.getElementById("randomNumber").innerHTML = number;
        };
     </script>
 </head>

fiddle : http://jsfiddle.net/yyAf8/

EDIT as per updated question:

<head>
   <script type="text/javascript">
     window.onload = generateRandomNumber;
     function generateRandomNumber(){
         var n = 25;
         var number = Math.floor(Math.random()*n)+1;
         document.getElementById("randomNumber").innerHTML = number;
        }
  </script>
</head>

fiddle : http://jsfiddle.net/yyAf8/1/

uploading snapshot on demand by OP:

enter image description here enter image description here

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

3 Comments

It doesn't work when the code is put in an html file. Can you show what the whole code looks like?
uploaded snapshot in the answer.
It wasn't working because I was setting value and not innerHTML.
3

Because in your script you use an element that is not defined yet. Put the script after the element.

Demo: http://jsbin.com/upihez/2

4 Comments

OK that worked, but is there a way I can still keep the javascript code in in the head? Can I use onload to do this?
I put it in a function and updated the code in my question. Why doesn't it work?
Because this time generateRandomNumber doesn't exist! Do this: window.onload = function() {...}
That didn't work. Can you show what my code looks like when it's fixed?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.