Emil Gurbanov Emil Gurbanov - 16 days ago 5
Javascript Question

Get text area value and store it in a div with line breaks using JavaScript

I need to get a text from Textarea element and save the text into a div keeping line breaks obtained by pressing Enter key. But the code I am using does not seem to be good enough :)
Could you please take a look at the code below and share a suggestions on how to achieve such result:

JS

var div = $('div');
var textarea = $('textarea');

textarea.keyup(function(e){
if(e.keyCode === 13){
div.text(textarea.val() + "\n")
}
})


Result div:

enter image description here

Result using
instead of the \n

enter image description here

Answer

You should use

<br/> instead of \n for new line in Html

Also use .append() instead of .text()

Comments