Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

190
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!