Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

191
Visualizações
Javascript ignores last linebreak with text.(elem.val())

I'm trying to output a textarea value into a pre (or a div with white-space:pre for that matter). All works well, but it skips the last linebreak. So, if you add text and a linebreak, it won't display the linebreak. If you add text and two linebreaks, it displays text and one linebreak. So, it looks like the text is being trimmed. Can anyone suggest why this is happening and how to solve it?

function starter(e) {
  $("#output").text(e);
}

$('#textin').on('input',function(){
  starter($('#textin').val())
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea id="textin"></textarea>
<pre id="output" style="border:1px solid black"></pre>

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

I found an answer after reading When are <br> elements ignored when within a paragraph?.

Browsers take a line break not as a line break, but more like 'end of line'.

With that in mind; this semi-dirty trick does the job, adding an extra line break:

function starter(e) {
  $("#output").text(e+'\n');
}
about 4 years ago · Juan Pablo Isaza Relatório

0

The easiest solution is to simply style the element you're inserting the text into with the following CSS property:

white-space: pre-wrap;

This property causes whitespace and newlines within the matching elements to be treated in the same way as inside a <textarea>. That is, consecutive whitespace is not collapsed, and lines are broken at explicit newlines (but are also wrapped automatically if they exceed the width of the element).

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda