-4

I'm trying to output the data in an array (produced by this code) to a div in a simple web page, using this jquery:

$('#submit').click(function(e) {
        e.preventDefault();    
        var num = $('#userInput').val();       
        var primes = sieve(num);          // sieve() produces array of prime numbers
        console.log(primes);          
        $('#answer').html(primes);
    });

The console is logging the array as I would like to see it, (i.e. 2, 3, 5, 7, 11, 13, etc.) but the content in #answer is displaying without any formatting (23571113 etc.).

How can I get the data to display in a more readable format? I've tried using .split and .join to add commas or line breaks but no joy...

Community
  • 1
  • 1

2 Answers2

6

Just join the array into a string using whatever separator you want to use. Also, when filling in text that isn't HTML, don't use html, use text:

$('#answer').text(primes.join(", "));

You (and lurkers) may be wondering why you didn't get the default Array#toString behavior, which is to do .join() (where join defaults to the separator ","). The reason is that the html function is appending each element of the array to the target element individually, as a new text node, instead of calling toString on the array. (This doesn't appear to be documented behavior.) Surprising, but true:

var answer = $("#answer");
answer.html([1, 2, 3, 4, 5]);
console.log(answer[0].childNodes.length); // 5
<div id="answer"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

text applies toString, but the default separator used (",", no space after ,) probably isn't what you want:

var answer = $("#answer");
answer.text([1, 2, 3, 4, 5]);
console.log(answer[0].childNodes.length); // 5
<div id="answer"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

An easy way would be to use .text() instead of .html() to set the contents of the #answer element. You must also join the values of the array using the .join() method.

$('#submit').click(function(e) {
        e.preventDefault();    
        var num = $('#userInput').val();       
        var primes = sieve(num);          // sieve() produces array of prime numbers
        console.log(primes);          
        $('#answer').text(primes.join(", "));
    });

Or, if you really want to add it as HTML, wrap it in a pre element, which preserves whitespace:

$('#submit').click(function(e) {
        e.preventDefault();    
        var num = $('#userInput').val();       
        var primes = sieve(num);          // sieve() produces array of prime numbers
        console.log(primes);          
        $('#answer').html('<pre>' + primes.join(", ") + '</pre>');
    });
HaukurHaf
  • 13,522
  • 5
  • 44
  • 59