0

I've got an array in Javascript that I want to print to screen which is: (my function for ro[j] is simplified in this example, but that doesn't matter)

<div class="result2"></div>
<script>
  var j;
  var ro = [0];
  for(j=0; j <= 49; j++){
    ro[j] = j;
    $('.result2').html(ro[j]);
  }
</script>

But this doesn't work as I think it keeps replacing the div with each loop rather than adding to the div. Is there a good way to implement this? I thought you could try something like this:

<div class="result2"></div>
<script>
  var j;
  var ro = [0];
  for(j=0; j <= 49; j++){
    ro[j] = j;
    if(j==0){
      $('.result2').html(ro[j]);
    }else{
      var res = $('.result2').val();
      $('.result2').html(res + ro[j]); 
    }
  }
</script>

but this doesn't work since you can't seem to call the result of the script midway through the script? Or I just made a mistake, I'm not sure. Any help would be great!

edit: forgot a semicolon

3
  • var res = $('.result2').html(); Commented Jun 14, 2018 at 14:03
  • Ah that makes sense, I was wondering why I couldn't' feed it back in. Thanks, that solves it! Commented Jun 14, 2018 at 14:09
  • 1
    Possible duplicate of how to print htmlString in loop with jquery Commented Jun 14, 2018 at 14:09

2 Answers 2

0

A list element (ul or ol) should be used for lists as it's more semantically correct:

<ul id="result2"></ul>

Using es6 syntax you can append elements to that list like this:

const ro = [...Array(49).keys()]; // Just setting up a sample array

for (r of ro) {
  let li = document.createElement('li');
  li.innerHTML = r;
  document.getElementById('result2').appendChild(li);
}
Sign up to request clarification or add additional context in comments.

Comments

-1

This will place the numbers vertically in the screen.

<!DOCTYPE HTML>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>

<body>
    <div class="result2"></div>
    <script type='text/javascript'>
        var ro = [];

        for (var j = 0; j <= 49; j++) {
            ro.push(j);
            $('.result2').append(ro[j] + '<br />');
        }
    </script>
</body>
</html>

1 Comment

This seems very awkward, you should setup ro with 49 entries before looping through it.

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.