I am tying to make a simple effect using keyup()
in jQuery. I just want that when user types into the textarea
then the text which user types will copy to another div named .content
. When I press enter in textarea a new line is created but in my div the text is showing in the same line. My code is below or you can see demo here: http://jsfiddle.net/Pqygp/
$('.content:not(.focus)').keyup(function(){
var value = $(this).val();
var contentAttr = $(this).attr('name');
$('.'+contentAttr+'').html(value);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea name="mas" rows="15" class="content"></textarea>
<p> </p>
<div class="mas" >Texts Comes here</div>
To preserve line breaks when getting text from a textarea with JavaScript, we can replace whitespace characters with '<br>\n' . const post = document. createElement("p"); post. textContent = postText; post.
To add line breaks to a textarea, use the addition (+) operator and add the \r\n string at the place where you want to add a line break, e.g. 'line one' + '\r\n' + 'line two' . The combination of the \r and \n characters is used as a newline character.
Just put the output text between <pre></pre> tags, that will preserve the line breaks.
You cannot place HTML elements inside a text area, only text content. only text content covers that part.
Add a white-space: pre-wrap
rule to the div's CSS.
.mas {
white-space: pre-wrap;
}
Demo: http://jsfiddle.net/Pqygp/13/
You need to convert the literal newlines into <br>
tags for proper output in the DIV.
$('.'+contentAttr+'').html(value.replace(/\r?\n/g,'<br/>'));
Shown in your code below:
$('.content:not(.focus)').keyup(function(){
var value = $(this).val();
var contentAttr = $(this).attr('name');
$('.'+contentAttr+'').html(value.replace(/\r?\n/g,'<br/>')); //convert newlines into <br> tags
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <textarea name="mas" rows="15" class="content"></textarea> <p> </p> <div class="mas" >Texts Comes here</div>
JSFiddle
Use this line: Fiddle
$('.'+contentAttr+'').html(value.replace(/\n/g,"<br>"));
The problem was that newlines don't create linebreaks in html, but <br>
will.
Try like
var value = $(this).();
var contentAttr = $(this).attr('name');
$('.'+contentAttr+'').html(value.replace(/\r?\n/g,"<br>"));
This is the DEMO
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With