Reputation: 37377
I'm doing something very similar to the stackoverflow question preview only much more basic.
user types in text area -> keyup shows what they've typed in preview
new lines aren't working
$('input, textarea').keyup(function(){
var value = $(this).attr('value').replace('\n', '<br />').replace('\r', '<br />');
$('p.preview').html(value);
})
Upvotes: 0
Views: 719
Reputation: 44376
jQuery.val()
rather than jQuery.attr()
You could use CSS white-space: pre-line
property which do exactly what you want:
$("input, textarea").keyup(function() {
$("p.preview").html($(this).val());
});
p.preview {
white-space: pre-line;
}
Upvotes: 0
Reputation: 630379
You need something like this:
$('input, textarea').keyup(function(){
var value = $(this).attr('value').replace(/\n/g,'<br/>').replace(/\r/g,'');
$('p.preview').html(value);
});
Note the /g
,which you need to replace more than the first occurance, and we're replacing only one of the returns, so you don't get 2 line returns in your preview per 1 in the textarea/input.
Upvotes: 1