line breaks or pharagraph not working in textarea output? for example i am using enter for pharagraph in textarea but not working in output? How can i do that?
$("#submit-code").click(function() {
$("div.output").html($(".support-answer-textarea").val());
}).next().click(function () {
$(".support-answer-textarea").val($("div.output").html());
});
.support-answer-textarea{width:100%;min-height:300px;margin:0 0 50px 0;padding:20px 50px;border-top:1px solid #deddd9;border-bottom:1px solid #deddd9;border-left:none;border-right:none;box-sizing:border-box;letter-spacing:-1px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<textarea id="support-answer-textarea" class="support-answer-textarea" placeholder="Destek Konusunu Cevapla!"></textarea>
<button type="submit" id="submit-code" class="btn btn-success">Submit Your Code</button>
<div class="output"></div>
To preserve line breaks when getting text from a textarea with JavaScript, we can replace whitespace characters with '<br>\n' .
\n is the linefeed character literal (ASCII 10) in a Javascript string. <br/> is a line break in HTML. Many other elements, eg <p> , <div> , etc also render line breaks unless overridden with some styles.
Talking specifically about textareas in web forms, for all textareas, on all platforms, \r\n will work.
Just put the output text between <pre></pre> tags, that will preserve the line breaks.
The best and easy way to fix line breaks on the output use these simple css:
.support-answer-textarea {
white-space: pre-wrap;
}
When you hit enter
in a <textarea>
, you're adding a new line character \n
to the text which is considered a white space character in HTML. HTML generally converts the sequence of all white spaces to a single space. This means that if you enter a single or a dozen of whitespace characters (space, new line character or tab) in a row, the only effect in resulting HTML is just a single space.
Now the solution. You can substitute the new line character (\n
) to <br>
or <p>
tag using replace()
method.
$("#submit-code").click(function() {
$("div.output").html($(".support-answer-textarea").val().replace(/\n/g, "<br>"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<textarea id="support-answer-textarea" class="support-answer-textarea"></textarea>
<button type="submit" id="submit-code">Submit Your Code</button>
<div class="output"></div>
for me, I had a e.preventDefault()
for only Enter
keypress on a parent element, this prevents a new line from adding.
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