7

I have read this question/answer and this one, but I can't get it to work in my situation.

I'm building a list of names from a json array returned from a php script. After the below code I'm putting the goTosList string into a label via jquery. I need each name to be on a new line.

The below code is just outputting

var goTosList = '';
if (data !== 'empty') {
    // Build the go tos list as a comma-separated string
    $.each(data, function(index,element) {
        goTosList += (element['name'] === undefined ? '' : element['name']) + '\n\r';
    });
}

I've tried just \r and just \n and without the single quotes. I can't get it to work.

Community
  • 1
  • 1
marky
  • 4,878
  • 17
  • 59
  • 103

1 Answers1

13

If you are output is HTML and you want newlines you have two options:

Either use a <pre> tag as a wrapper to your text (not suitable here I think)

<pre>some Text

with newlines</pre>

or add <br> instead of \n\r:

some Text<br>with newlines

So in your code this would translate to

goTosList += (element['name'] === undefined ? '' : element['name']) + '<br>';

and later on insert this into the DOM by

$('#yourLabel').html( goTosList );
Sirko
  • 72,589
  • 19
  • 149
  • 183
  • 1
    Thanks for the quick reply, but that didn't work. Adding `
    ` as you suggest just adds the tag as text. It's rendered in the label as "John Smith
    Mary Johnson".
    – marky May 28 '13 at 13:43
  • @eventide Which command do you use to insert the text in the page? – Sirko May 28 '13 at 13:47
  • 2
    As soon as I read your question I realized that was the problem. I was using `$('#label').text(goTosList);` Changing `.text` to `.html` fixed it. Thanks! – marky May 28 '13 at 13:59
  • I also want to add line number, Is it possible? – Varun Sharma Dec 19 '18 at 07:53
  • @VSH Not sure, what you are up to. At the point where you create the string to be inserted, you can obviously also add line numbers, but I don't see the connection to this question. – Sirko Dec 19 '18 at 08:28
  • https://stackoverflow.com/questions/53845228/how-to-put-line-number-in-source-code-after-parse-in-html-page – Varun Sharma Dec 19 '18 at 08:42