Sophonias
Sophonias

Reputation: 914

How to display the contents of textbox, in a preview div?

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?

Upvotes: 1

Views: 3332

Answers (2)

Girish Sakhare
Girish Sakhare

Reputation: 763

$(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.

Upvotes: 0

rajesh kakawat
rajesh kakawat

Reputation: 10896

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>

Upvotes: 3

Related Questions