views:

61

answers:

2

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);
    })
+1  A: 

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.

Nick Craver
perfect!didnt realise replace only changes one value,will merge into a single regexthanks again!
Haroldo
A: 
  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;
    }
    
Crozin