JavaScript: ¿Cómo agregar saltos de línea a un área de texto HTML?


Estoy editando un área de texto con JavaScript. El problema es que cuando hago saltos de línea en él, no se mostrarán. ¿Cómo puedo hacer esto?

Estoy obteniendo el valor para escribir una función, pero no dará saltos de línea.

Author: djairo, 2009-05-14

9 answers

El problema viene del hecho de que los saltos de línea (\n\r?) no son lo mismo que HTML <br/> etiquetas

var text = document.forms[0].txt.value;
text = text.replace(/\r?\n/g, '<br />');
 242
Author: TStamper,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-03 12:13:11

Si utiliza java script general y necesita asignar una cadena al valor del área de texto, entonces

 document.getElementById("textareaid").value='texthere\\\ntexttext'.

Debe reemplazar \n o < br > a \\\n

De lo contrario da Uncaught SyntaxError: Unexpected token ILLEGAL en todos los navegadores.

 21
Author: jit,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-03-05 13:51:22

Tal vez alguien encuentre esto útil:

Tuve problemas con los saltos de línea que se pasaron de la variable del servidor a la variable javascript, y luego javascript los escribía en textarea (usando knockout.enlaces de valores js).

La solución era el doble escape de nuevas líneas:

orginal.Replace("\r\n", "\\r\\n")

En el lado del servidor, porque con solo caracteres de escape simples javascript no estaba analizando.

 12
Author: 0lukasz0,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-05-31 13:59:35

Necesitas usar \n para linebreaks dentro de textarea

 12
Author: strubester,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-20 15:28:16

Una nueva línea es solo un espacio en blanco para el navegador y no se tratará de manera diferente a un espacio normal (" "). Para obtener una nueva línea, debe insertar elementos <BR />.

Otro intento de resolver el problema: Escriba el texto en el área de texto y luego agregue un poco de JavaScript detrás de un botón para convertir los caracteres invisibles a algo legible y volcar el resultado a un DIV. Eso le dirá lo que su navegador quiere.

 3
Author: Aaron Digulla,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-05-14 14:54:28

Tengo un área de texto con id es #infoartist seguir:

<textarea id="infoartist" ng-show="dForm" style="width: 100%;" placeholder="Tell your contacts and collectors about yourself."></textarea>

En código javascript, obtendré el valor de textarea y reemplazaré la nueva línea de escape (\n \ r) por la etiqueta <br />, como:

var text = document.getElementById("infoartist").value;
text = text.replace(/\r?\n/g, '<br />');

Así que si estás usando jquery (como yo):

var text = $("#infoartist").val();
text = text.replace(/\r?\n/g, '<br />');

Espero que te haya ayudado. :-)

 2
Author: NgaNguyenDuy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-03-30 19:50:45

Si desea mostrar texto dentro de su propia página, puede usar la etiqueta <pre>.

document.querySelector('textarea').addEventListener('keyup', function() {
  document.querySelector('pre').innerText = this.value;
});
<textarea placeholder="type text here"></textarea>
<pre>
The
new line will
be respected
</pre>
 1
Author: Cristian Traìna,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-29 10:43:59

Si solo necesita enviar el valor de la zona de prueba al servidor con saltos de línea, use nl2br

 0
Author: Igor L.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-03-05 13:17:25

Aquí está lo que hice por el mismo problema que tuve.

Cuando estoy pasando el texto a la página siguiente en jsp, lo estoy leyendo como un área de texto en lugar de leer algo como

Así que la salida vino como querías. y para otras propiedades, puede usar lo siguiente.

<textarea style="background-color: white; border: none; width:660px;font-family: Arial, Helvetica, sans-serif; font-size:1.0em; resize:none;" name="text" cols="75" rows="15" readonly="readonly" ><s:property value="%{text}"/></textarea>
 0
Author: raja777m,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-10-23 22:29:25