Haroldo
Haroldo

Reputation: 37377

how to do new lines? [ textarea -> jquery -> p tag ]

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

Answers (2)

Crozin
Crozin

Reputation: 44376

  1. To get value use jQuery.val() rather than jQuery.attr()
  2. 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

Nick Craver
Nick Craver

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

Related Questions