简体   繁体   中英

JS - How to start from new line inside for loop?

I am trying to print 6 random numbers after clicking a button. Then every time I click the button again, random numbers should start from new line however I do not know how. I tried everything and nothing works. I appreciate any help.

  function fname() { for(i=1; i<=6; i++) { number = number + Math.floor(Math.random() * 47 + 1) + "-"; var print = number + " GOOD LUCK!"; } document.getElementById("total").value = print; } 
 <!DOCTYPE html> <html> <head> <title>Let's ROLL!</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <style> input, button {display: block;} </style> <script> var number = ""; function fname() { for(i=1; i<=6; i++) { number = number + Math.floor(Math.random() * 47 + 1) + "-"; var print = number + " GOOD LUCK!"; } document.getElementById("total").value = print; } </script> </head> <body> <div> <button onclick="fname()">ROLL!</button> <textarea id="total" rows="12" cols="50" readonly></textarea> </div> </body> </html> 

Not 100% clear on where you wanted the breaks, but in a text area, a line break is \\n . If this was in an HTML element, you would use <br /> .

 var number = ""; function fname() { for (i = 1; i <= 6; i++) { number = number + Math.floor(Math.random() * 47 + 1) + "-"; } number = number + "\\n"; var print = number + "GOOD LUCK!"; document.getElementById("total").value = print; } 
  input, button { display: block; } 
 <div> <button onclick="fname()">ROLL!</button> <textarea id="total" rows="12" cols="50" readonly></textarea> </div> 

Add "\\n".

I am assuming you want to concatenate the new text in the text area, so you should use += instead of =:

document.getElementById("total").value += print + "\n";

You can use arrays and .join() the numbers and lines together by their appropriate delimiters. This only inserts the characters between the elements. \\n in a string renders a new line.

 var button = document.getElementById('roll'); var total = document.getElementById('total'); var rolls = []; button.onclick = function() { var roll = []; for(var i=0; i<6; ++i) roll.push(Math.floor(Math.random() * 47 + 1)); rolls.push(roll.join('-')); total.value = rolls.join('\\n') + "\\nGOOD LUCK!"; } 
 <button id="roll">ROLL!</button><br> <textarea id="total" rows="12" cols="50" readonly></textarea> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM