3

I have following small script to preview some text before submitting it to store in a database:

jQuery(function($) {
    var input = $('#contents'),
    preview = $('#previewaccordion div.viewcontents');

    input.keyup(function(e) {
        preview.html(input.val());
    });
});

but if I type text with line-breaks it ignores them and writes all of them in one line. How could I replace the line-breaks so that they show correctly?

Leniel Maccaferri
  • 100,159
  • 46
  • 371
  • 480
Tamara
  • 33
  • 1
  • 3

4 Answers4

5

It's nothing to do with jQuery: Linebreaks in HTML are not significant, they're just whitespace (like spaces and tabs).

To force a linebreak in HTML, you use a <br> tag. So you could change

preview.html(input.val());

to

preview.html(input.val().replace(/\r?\n/g, '<br>'));

Note that you're also not escaping HTML special characters (like < or &), and so if you type them, your output may not be correct. So you might go with:

preview.html(input.val().replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/\r?\n/g, '<br>'));

And finally, I'd hook keypress as well as keyup, so you see characters created via key repeat (which fires keypress, but not keyup).

Live example | source

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
5

I assume that you are using a textarea for the input. There are \n used as linebreaks, which have no influence in HTML. So you have to replace them with br-tags:

input.val().replace(/\n/g, "<br />");
Daniel Rotter
  • 1,998
  • 2
  • 16
  • 33
3

Hiya demo here: http://jsfiddle.net/STnhV/1/

hope this helps! cheers!

Jquery Code:

$(document).ready(function() {
    $('#inputfoo').keyup(function() {
       $('#outputbar').html($(this).val().replace(/\n/g,'<br/>')); 
    });
});

​
Tats_innit
  • 33,991
  • 10
  • 71
  • 77
0

Replace the linebreaks to html break tags when you render the output from the database.

Willem D'Haeseleer
  • 19,661
  • 9
  • 66
  • 99