0

I'm new to html and javascript. How can I display the for loop that I have in my javascript function on the same page upon clicking the button. Right now I click the button and it brings me to a whole different page displaying 0 to -99. I want the numbers to appear below the button on the same page. Any ideas?

         <fieldset>
         <legend>Loop Until -99</legend>
         <form name="loopuntil99" method="post">
         <input type="button" value="Display -99" onclick="displayArray()" />
         </form>
         </fieldset>

         </body>

         <script type="text/javascript">
       function displayArray()
       {

      for (i=0;i>-100;i--)
      {

    document.write(i + ", ");

       } 
        }

    </script>

     </html>

2 Answers 2

1

You can add a div and just modify the HTML in that.

    <div id="output"></div>
</body>
<script type="text/javascript">
function displayArray()
{
    var div = document.getElementById("output");
    div.innerHTML = "0";
    for (i=-1;i>-100;i--)
    {
        div.innerHTML += ", " + i;
    } 
}
</script>
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks it works. Would this be the simplest way to do this? b/c I need to create some kind of basic menu. I need to allow the user to enter 10 numbers and put it into array. With that array I need to display different things like reverse order, sort ,ect.. So I guess what I'm asking is would I need to createa <div id/> for each different function I would want to print out?
Or better yet, lets say I click another button that calls a different function that will have a different output. How would I update and replace output with the results from the second function
You can add as many divs as you need. You reference the div in JavaScript using the id in document.getElementById, then set the innerHTML property like above.
1

Looks like you are outside the <body> tag. Place that code before the </body> tag and try again.

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.