0

Trying to display a list of numbers 000-999.
I keep getting this error thrown on the last line: Cannot set property 'value' of null

Code:

<head>

<title>Display 000 through 999</title>

<meta http-equiv="content-type"content="text/html; charset=iso-8859-1" />
<script type="text/javascript">

var digit1 = 0;
var digit2 = 0;
var digit3 = 0;

while (digit1 <= 9) {
    while (digit2 <=9) {
        while (digit3 <=9){
            digit3++;
        }
        digit2++;
    }
    digit1++;   
}

document.getElementById('display').value = digit1 + digit2 + digit3;


</script>
</head>

<body>

<p id="display"></p>

</body>
UKXK189
  • 17
  • 4
  • 1
    The error indicates that there is no `document.getElementById('display')` element. It has nothing to do with `digit1`, `digit2` or `digit3`. – LostMyGlasses Sep 20 '15 at 16:43
  • 1
    To confirm what we all suspect, you should post your html so we can see if there is an element with that id. – takendarkk Sep 20 '15 at 16:44
  • I added the html per request – UKXK189 Sep 20 '15 at 17:01
  • The element exists, so `.value` is the issue. Use `.innerHTML`. And see my answer below for another problem with your code – Reeno Sep 20 '15 at 17:02
  • 1
    `.value` is not the issue, the error message would be different. It seems to me that the problem is that the script is contained in the ``, which causes the JavaScript code to be executed before the `display` element is created. – LostMyGlasses Sep 20 '15 at 17:08
  • @Nico is correct. The initial error is happening because the HTML element with the ID "display" does not exist at the time that the JavaScript executes. – Jack A. Sep 20 '15 at 17:28

1 Answers1

0

Does an element with id 'display' exist? If yes, use document.getElementById('display').innerHTML to set the content:

var digit1 = 0;
var digit2 = 0;
var digit3 = 0;

while (digit1 <= 9) {
    while (digit2 <=9) {
        while (digit3 <=9){
            digit3++;
        }
        digit2++;
    }
    digit1++;   
}

document.getElementById('display').innerHTML = ('<br />' + digit1 + digit2 + digit3);

Demo: http://jsfiddle.net/8w8znpqn/

But I think your complete JS is wrong. If you want the numbers from 000-999 use this:

var str = '';
// loop through all numbers from 0 to 999
for(var i = 0; i < 1000; i++) {
    // add the number to "str"
    // this strange "'000'.substring(0, 3 - i.toString().length)"
    // is to get the leading zeros, see http://stackoverflow.com/a/5366862/1682509
    str = str  + '000'.substring(0, 3 - i.toString().length) + i + '<br />';
}

document.getElementById('display').innerHTML = (str);

Demo: http://jsfiddle.net/8w8znpqn/1/

Reeno
  • 5,720
  • 11
  • 37
  • 50