57

I'm sending variables to a text box as a concatenated string so I can include multiple variables in on getElementById call.

I need to specify a line break so the address is formatted properly.

document.getElementById("address_box").value = 
(title + address + address2 + address3 + address4);

I've already tried \n after the line break and after the variable. and tried changing the concatenation operator to +=.

Fixed: This problem was resolved using;

document.getElementById("address_box").value = 
(title + "\n" + address + "\n" + address2 + "\n" +  address3 +  "\n" + address4);

and changing the textbox from 'input type' to 'textarea'

blarg
  • 3,653
  • 9
  • 38
  • 64
  • I would have up-voted this question however you accepted a not-an-answer as an answer. ︎ – John Aug 22 '18 at 02:37

4 Answers4

60

You can't have multiple lines in a text box, you need a textarea. Then it works with \n between the values.

Guffa
  • 666,277
  • 106
  • 705
  • 986
24
document.getElementById("address_box").value = 
(title + "\n" + address + "\n" + address2 + "\n" + address3 + "\n" + address4);
jnovack
  • 6,131
  • 2
  • 24
  • 40
10

You need to use \n inside quotes.

document.getElementById("address_box").value = (title + "\n" + address + "\n" + address2 + "\n" + address3 + "\n" + address4)

\n is called a EOL or line-break, \n is a common EOL marker and is commonly refereed to as LF or line-feed, it is a special ASCII character

FabianCook
  • 19,591
  • 16
  • 64
  • 112
Chirag Bhatia - chirag64
  • 4,224
  • 2
  • 24
  • 34
5

Using Backtick

Backticks are commonly used for multi-line strings or when you want to interpolate an expression within your string

let title = 'John';
let address = 'address';
let address2 = 'address2222';
let address3 = 'address33333';
let address4 = 'address44444';
document.getElementById("address_box").innerText = `${title} 
${address}
${address2}
${address3} 
${address4}`;
<div id="address_box">
</div>
akhtarvahid
  • 8,226
  • 2
  • 18
  • 27