I have a pagaraph (p
) appended to a div
, that shows <textarea>
value, and it works well.
The <textarea>
supposed to be a part of a page that allows the users to add new lines to the text content, exactly like how we can type <br>
for a new line in textarea
.
But since they don't know how to do that I'm trying to make it easy for them by:
(typing plus sign twice ++ OR pressing Enter on the keyboard)
Both should add a <br>
tag automatically while typing (onkeyup)
...
var textarea = document.getElementById('textarea');
var textareaPreview = document.querySelector('.textarea-preview');
var currentText;
textarea.onkeyup = function(){
currentText = textarea.value;
var previewAsString = "<p class='p-preview'>" + currentText + "</p>"
textareaPreview.innerHTML = previewAsString;
};
textarea {
width: 300px;
height: 80px;
resize: vertical;
}
<div class="block">
<textarea id="textarea" placeholder="Type here.."></textarea>
</div>
<div class="block">
<div class="textarea-preview"></div>
</div>
To add text to a textarea, access the value property on the element and set it to its current value plus the text to be appended, e.g. textarea. value += 'Appended text' . The value property can be used to get and set the content of a textarea element.
From the MDN documentation: " <textarea> does not support the value attribute".
Use the value property to get the value of a textarea, e.g. const value = textarea. value . The value property can be used to read and set the value of a textarea element. If the textarea is empty, an empty string is returned.
It sounds like all you need is to replace ++
and newlines with <br>
:
var textarea = document.getElementById('textarea');
var textareaPreview = document.querySelector('.textarea-preview');
var currentText;
textarea.onkeyup = function(){
currentText = textarea.value;
var previewAsString = "<p class='p-preview'>" + currentText.replace(/\+\+|\n/g, '<br>') + "</p>"
textareaPreview.innerHTML = previewAsString;
};
textarea {
width: 300px;
height: 80px;
resize: vertical;
}
<div class="block">
<textarea id="textarea" placeholder="Type here.."></textarea>
</div>
<div class="block">
<div class="textarea-preview"></div>
</div>
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