Breaking array array jQuery

1

I am collecting the values selected by the user and playing them in an array. After that, I created a loop to throw those values into a string to print on the screen. The problem is they are all coming in a row just with a space between them. Here is the code for 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);
    
asked by anonymous 14.03.2017 / 20:10

2 answers

0

Three alternatives:

  • How do you have and join white-space: pre-wrap; in CSS
  • using <br> as separator and .html() instead 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><divid="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><divid="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><divid="itens"></div>
    
14.03.2017 / 20:26
0

Instead of concatenating \n you should concatenate <br/> since the content you are printing is HTML.

You should also invoke method .text(descr) instead of calling .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><pid="itens"></p>
    
14.03.2017 / 20:19