Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - updating <textarea> value under certian conditions and append it to a <div>

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>
like image 685
001 Avatar asked Nov 04 '20 22:11

001


People also ask

How to add value to textarea in JavaScript?

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.

Can we use value attribute in textarea?

From the MDN documentation: " <textarea> does not support the value attribute".

How do you value a text area?

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.


1 Answers

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>
like image 185
CertainPerformance Avatar answered Nov 04 '22 11:11

CertainPerformance