Phil
Phil

Reputation: 993

jQuery onInput recognize line break

To provide a preview of an entry I use jQuery as the following

$('#text').on('input',function(){
    $('#previewText').html($('#text').val());
});

#text is a textarea and #previewText a simple <p>

It works very well except at one point: It does not recognize when I hit ENTER. Instead of the wanted line break it simply writes on in the same line.

Is there any possibility to achieve the recognizing of line breaks with this method?

Upvotes: 2

Views: 364

Answers (2)

Ayush
Ayush

Reputation: 311

Try using this: As in case of textarea, it is a new line character and in html for new line we use a
tag. So the idea is to replace the textarea's new line char with the
tag. Working example: http://jsfiddle.net/qh6cepp7/

$('#text').keypress(function(event){ 
    var keycode = (event.keyCode ? event.keyCode : event.which);
    $('#previewText').html($('#text').val().split("\n").join("<br>"));
});

Upvotes: 0

Ahs N
Ahs N

Reputation: 8366

Change your code from this:

$('#text').on('input',function(){
    $('#previewText').html($('#text').val());
});

to this:

$('#text').on("input", function () {
        $('#previewText').html($(this).val().replace(/\n/g, "<br/>"));
});

Here is the JSFiddle demo

What the modified code does is that it replaces the line breaks character "\n" to "<br/>" which is the HTML version of standard line break.

Upvotes: 2

Related Questions