Michael
Michael

Reputation: 13636

Add string to new line in textarea element

I want to insert string from a new row to my textarea HTML element.

I have this textarea element:

<textarea id="txtLogs" rows="13" cols="220"></textarea>

At some point I add text to the element above:

document.getElementById('txtLogs').value = 'tileloadStart...' + ' ' + layer.get('name') + ' ' + myTime;

And after some time again:

document.getElementById('txtLogs').value = 'tileloadEnd...' + ' ' + layer.get('name') + ' ' + myTime;

Every time I add a string to the textarea element it is added to the same row while I need the new string to be inserted to new row.

How do I change in my code to add a string to textarea element and display it in the new row?

Upvotes: 0

Views: 339

Answers (2)

Nicolas
Nicolas

Reputation: 8695

You need to add a return character aswell ( \n )

document.querySelector('.btn').onclick = () => {
  let newRowString = "something on a new Row";
  let otherNewRowString = "Something else on a new row";


  let currentValue = document.getElementById('txtLogs').value;
  document.getElementById('txtLogs').value = currentValue + '\n' + 'tileloadStart...' + '\n' + newRowString + '\n' + otherNewRowString; 
};
<textarea id="txtLogs"></textarea>

<button class="btn">add new row</button>

Upvotes: 0

Sebastian Kaczmarek
Sebastian Kaczmarek

Reputation: 8515

You can add newline (\n) at the end of each line. Also, don't forget that we're appending the new lines so you have to use +=:

 document.getElementById('txtLogs').value = 'first line\n';
 document.getElementById('txtLogs').value += 'second line\n';
 document.getElementById('txtLogs').value += 'third line\n';
 <textarea id="txtLogs" rows="13" cols="220"></textarea>

Upvotes: 3

Related Questions