0

this is shan and i'm a javascript noob and i'm trying to work qa code as an example here. i'm trying to load a small javascript content to a div element but it is not working any help would be great and here is the code.

<html>
<head>
    <title>
    using d for statement
</title>
<script>
    function displaytext () {
     var loopindex=0;
     var sum=0;
     for (var loopindex=1; loopindex <=100; loopindex++) {
       sum +=loopindex;
     }; 
    document.getElementById('targetdiv').innerhtml="adding 1 to 100 gives "+sum;
    }
</script>
</head>
<body>
    <div id="targetdiv">

    </div>
</body>
</html>
jackal4me
  • 1
  • 4

2 Answers2

1

You need to call the function. It's also a good idea to wait until the window is loaded (or you can use some more advanced JS to detect the DOM ready state.):

<html>
<head>
    <title>
    using d for statement
</title>
<script>
    function displaytext() {
     var loopindex=0;
     var sum=0;
     for (var loopindex=1; loopindex <=100; loopindex++) {
       sum +=loopindex;
     }; 
    document.getElementById('targetdiv').innerHTML = "adding 1 to 100 gives "+sum;
    }
    window.onload = function(){
      displaytext();
    }
</script>
</head>
<body>
    <div id="targetdiv">

    </div>
</body>
</html>
Community
  • 1
  • 1
HellaMad
  • 4,908
  • 6
  • 29
  • 51
0

3 problems:

  1. You never actually call the function. It is only declared.
  2. The property is innerHTML not innerhtml. Javascript is case-sensitive.
  3. The script is above an element is is referencing. As scripts are executed as they are found (page construction is paused during execution) the element you are referring to is never found.

Also you declare the loopindex variable twice, which i think will cause a syntax error on ES5 strict.

<html>
    <head>
        <title>
        using d for statement
        </title>
    </head>
    <body>
        <div id="targetdiv">

        </div>
    </body>
    <script>
        function displaytext () {
         var sum=0;
         for (var loopindex=1; loopindex <=100; loopindex++) {
           sum +=loopindex;
         }; 
        document.getElementById('targetdiv').innerHTML="adding 1 to 100 gives "+sum;
        }
        displaytext();
    </script>
</html>
Iain
  • 2,091
  • 14
  • 18