Lim Soo Zhin
Lim Soo Zhin

Reputation: 13

How to add multiple lines without wiping the whole page?

I would like to print out the ":::" multiple times. However, using this code, I can only print the last line. How can I print all of these lines?

<body>
    <script>

        function tri(){
            var radius;

            radius = parseInt(document.getElementById("r").value);

            for (var i = 0; i < radius; i++){
                for (var j = 0; j < i; j++){
                    document.getElementById("triOut").innerHTML = ":::";
                }
                document.getElementById("triOut").innerHTML = "<br>";
            }

            for (var i = 0; i < radius; i++){
                for(var j = 0; j < radius-i; j++){
                    document.getElementById("triOut").innerHTML = ":::";
                }
                document.getElementById("triOut").innerHTML = "<br>";
            }

        }

    </script>


    Give me a number <input type="text" id="r"><button onclick="tri()"> Click here! </button>
    <p id="triOut"></p>

</body>

I expect something like

:::
::::::
:::::::::
::::::
:::

Instead, I got nothing shown on the screen.

Upvotes: 1

Views: 41

Answers (1)

j08691
j08691

Reputation: 208032

In your loops you overwrite the output when repeatedly using =. You want to concatenate with +=

function tri() {
  var radius;

  radius = parseInt(document.getElementById("r").value);

  for (var i = 0; i < radius; i++) {
    for (var j = 0; j < i; j++) {
      document.getElementById("triOut").innerHTML += ":::";
    }
    document.getElementById("triOut").innerHTML += "<br>";
  }

  for (var i = 0; i < radius; i++) {
    for (var j = 0; j < radius - i; j++) {
      document.getElementById("triOut").innerHTML += ":::";
    }
    document.getElementById("triOut").innerHTML += "<br>";
  }

}
Give me a number <input type="text" id="r"><button onclick="tri()"> Click here! </button>
<p id="triOut"></p>

Upvotes: 2

Related Questions