Breaking line array jQuery

Asked

Viewed 1,042 times

1

I am collecting the values selected by the user and playing in an array. After that, I created a loop to play these values in a string to print on the screen. The problem is that they’re all coming in one line with only one space between them. Follow code from the loop:

var descr = "";
for (var i = 0; i < nomes.length; i++) {
    descr = descr + "\n" + nomes[i] + ": " + qtd[i];
}
descr = descr + "\n";
$("#itens").text(descr);
  • And what do you want, that the text jumps line? The n could be replaced by <br>, but it depends on what it is #itens also.

  • #items is a <H2>

2 answers

0

rather than concatenate \n Voce must concatenate <br/> once the contents Voce is printing eh HTML.

You must also call instead the method .text(descr) call the method .html(descr)

var nomes = ['nome 1','nome 2','nome 3','nome 4','nome 5','nome 6'];
var qtd = ['1','2','3','4','5','6'];

var descr = "";
for (var i = 0; i < nomes.length; i++) {
    descr += "<br/>" + nomes[i] + ": " + qtd[i];
}
descr = descr + "<br/>";
$("#itens").html(descr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p id="itens"></p>

  • If I put "<br />", it appears on the screen. Ex: "Item 1 <br /> Item 2"

  • complemented the reply @lufizi had failed to quote the .html()

0


Three alternatives:

  • as you have and putting together white-space: pre-wrap; in the CSS
  • using <br> as separator and .html() in time of .text()
  • using <p></p>

#1

var nomes = ['Joao', 'Maria'];
var qtd = [10, 45];
var descr = "";
for (var i = 0; i < nomes.length; i++) {
  descr = descr + "\n" + nomes[i] + ": " + qtd[i];
}
descr = descr + "\n";
$("#itens").text(descr);
#itens {
  white-space: pre-wrap;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="itens"></div>

#2

var nomes = ['Joao', 'Maria'];
var qtd = [10, 45];
var descr = "";
for (var i = 0; i < nomes.length; i++) {
  descr = descr + "<br>" + nomes[i] + ": " + qtd[i];
}
descr = descr + "<br>";
$("#itens").html(descr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="itens"></div>

#3

var nomes = ['Joao', 'Maria'];
var qtd = [10, 45];
var descr = nomes.map(
  (nome, i) => ['<p>', nomes[i], ": ", qtd[i], '</p>'].join('')
);
$("#itens").html(descr);
#itens {
  white-space: pre-wrap;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="itens"></div>

  • Use the second option. It worked! Thank you

Browser other questions tagged

You are not signed in. Login or sign up in order to post.