Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery textarea value doesn't convert line breaks

When adding a string, set in JavaScript, to a textarea value, it seems to convert line breaks fine. However, when grabbing this string from a data attribute, it seems to leave the line breaks as \n

These both have type of string so I am confused how one works but not the other.

How can I grab the data attribute and make the line breaks work with a textarea?

<div id="test" data-message="this\ntest"></div>
<textarea id="textarea"></textarea>
<textarea id="textarea2"></textarea>
var html = 'this\ntest';
var div = $('#test').data('message');

$('#textarea').val(html);
$('#textarea2').val(div);

JSFiddle Example

like image 732
digitalclubb Avatar asked Dec 09 '13 09:12

digitalclubb


2 Answers

You need to use the HTML character entity for line break within an HTML property: &#13;

var html = 'this\ntest';
var div = $('#test').data('message');

$('#textarea').val(html);
$('#textarea2').val(div);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="test" data-message="this&#13;test"></div>
<textarea id="textarea"></textarea>
<textarea id="textarea2"></textarea>
like image 167
Rory McCrossan Avatar answered Sep 21 '22 02:09

Rory McCrossan


When you get it from the data attribute the\n is becoming escaped so you need to replace it:

$('#textarea2').val(div.replace("\\n","\n"));

Example

like image 42
Pete Avatar answered Sep 20 '22 02:09

Pete