KANAYO AUGUSTIN UG
KANAYO AUGUSTIN UG

Reputation: 2188

Creating a textarea preview before submission

Please guys, I want to create a page which works just like the STACKOVERFLOW that displays the texts instantly just exactly the way it's been writen when typing in a textarea, I am not to good at javascript but I did figure out this code:

$("#comment").keyup(function(){
    if($(this).val() == ""){
       $('#preview').css('display','none');
    }else{
       $('#preview').css('display','block');
    }
    $("#preview").html($(this).val());
    // $("#preview").text($(this).val()); // If you want html code to be escaped
    $("#preview").html($("#preview").html().replace(/`x3`/g,'<div id="code_put" class="code_put">'));
    $("#preview").html($("#preview").html().replace(/`z3`/g,'</div>'));
    var code = document.getElementById('code_put').innerHTML;
    $("#code_put").text(code);
    $("#code_put").html($("#code_put").html().replace(/!--/g,''));
    $("#code_put").html($("#code_put").html().replace(/--/g,''));
});

But It doesn't break down to the next line in the preview div when I press the enter key as it breaks down in the textarea. I guess this is not a better approach to achieving my aim. Please if anyone has a better approach to this I would appreciate it very much.

And if possible I also want the codings in the textarea to display in a gray div also just as in stackoverflow because I added something like such in my code but I guess that's not a better method of doing that.

here is the html code:

<textarea name="comment" id="comment" class="textarea"></textarea>
<div id="preview" class="preview">
</div>

it's not much and I guess its not relevant.

Thanks in Advance

Upvotes: 0

Views: 268

Answers (2)

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324790

The specific problem you mention in your post, namely that newlines aren't kept, can be fixed with a simple line of CSS:

white-space: pre-wrap;

However, there are other things wrong with your code. Most importantly, you are repeatedly assigning to the element's innerHTML (albeit through jQuery's .html() function) and reading from it too. You should almost never read from innerHTML...

Instead, start with preview = $(this).val();, then perform your various replacements or parsing on preview, and then finally, at the very end, $("#preview").html(preview);

Upvotes: 1

Samuel Reid
Samuel Reid

Reputation: 1766

If I'm understanding your situation correctly, I'd suggest either making your #preview <div> into a #preview <pre>, or adding this css:

#preview {
  white-space: pre;
}

That ought to make the newlines in the textarea show up correctly in the preview <div>.

Here's an example Fiddle: https://jsfiddle.net/00nmk83y/

Upvotes: 1

Related Questions