1

I am trying to display the value in a textarea in a div on keyup. I am having trouble displaying the line breaks. The text in my preview div appears inline. I tried to use replace and replaced the '/n' with '
' but it just displayed everything inline. This is my html and jquery code.

<input type="textarea" id="mytextarea"></textarea>
<div id="preview"></div>

$(document).ready(function () {    

      var content = $('#mytextarea').val();

      $('#mytextarea').keyup(function () {

          if ($('#mytextarea').val() != content) {
               content = $('#mytextarea').val().replace("\n", "<br />");

               $('#preview').text(content);            
           }
      });

});

Can anyone tell me how I can display the contents of the text area inside the preview div with the line breaks?

Sophonias
  • 874
  • 5
  • 16
  • 38

2 Answers2

3

try something like this

javascript code

    $(function(){
          var content = $('#mytextarea').val();
          $('#mytextarea').keyup(function () {
              if (this.value != content) {
                content = this.value.replace(/\n/g, "<br />");
                   $('#preview').html(content );            
               }
          });
    })

html code

    <textarea id="mytextarea"></textarea>
    <div id="preview"></div>
rajesh kakawat
  • 10,826
  • 1
  • 21
  • 40
0
$(document).ready(function () {    

  var content = $('#mytextarea').val();

  $('#mytextarea').keyup(function () {

      if ($('#mytextarea').val() != content) {
          content = $('#mytextarea').val().replace(/\\n/g, "<br />");

          $('#preview').text(content);            
       }
  });

});

Try this.

Girish Sakhare
  • 743
  • 7
  • 14
  • And here's the js fiddle with working demo http://jsfiddle.net/MyZgX/ – Girish Sakhare Dec 19 '13 at 09:15
  • Thanks for taking the time to put in a js fiddle but in the example you put there was for a textbox not a text area and the answer you gave yields exactly the same result my initial code did. Thank you for the effort though!! – Sophonias Dec 19 '13 at 16:46
  • @Sophonias please recheck the jsfiddle it is using text area as per your question. and I tried entering \n in it and its converting it to
    . But main thing is you should get answer so if you got it from any source that great and congrats!
    – Girish Sakhare Dec 20 '13 at 06:09
  • I rechecked the jsfiddle it still didnt work but I now know how to fix it. Change the input to (adding rows and columns) and change the function that replaces the the 'preview' tag with $("#preview").html(content). That should make it work!! – Sophonias Dec 20 '13 at 14:17