简体   繁体   中英

how to change paragraph with textarea

So I'm newbie in web development and I wanted to create paragraph that could change its textContent with textarea. I mean: if I would write 'Hello World!' in textarea, I wanted the content of paragraph change into text, that is written in the textbox. with JavaScript of course. but I have no idea how to do it. I had some tries but they all failed. Here is my HTML, I need JavaScript Tutor...

<p class="test-text"></p>

<textarea class="tarea" name="textarea" cols="30" rows="10"></textarea>

and variables that I created:

var paragraph = document.querySelector('.test-text');
var tarea = document.querySelector('.tarea');

Can u guys help me :D

I would give both an id, so you can get them easier. Using the classname might work, but if you want to make another element of that class it would not work. And if you are only using the classes to identify the elements, you should use id anyway, since this is what they are made for. It would then look like this:

<p class="test-text" id="myParagraph"></p>

<textarea class="tarea" id="myTextarea" name="textarea" cols="30" rows="10"></textarea>

Then you can simply set the textArea with this:

var text = document.getElementById("myParagraph").textContent;
document.getElementById('myTextarea').value = text;

Pls note that textContent only works as exspected if you have no other elements inside your paragraph tag. Otherwise the textContent of the underlying elements woould be included in the textContent of the paragraph element.

First you need to grab the elements:

HTML:
<p id="text" class="test-text"></p>

<textarea id="text-area" class="tarea" name="textarea" cols="30" rows="10"></textarea>

JS:
var paragraph = document.querySelector('#text');
var tarea = document.querySelector('#text-area');

I added ids for the elements

Then you need to add an event listener to the textarea:

tarea.addEventListener('input', updateValue);

Now you can create a function to update the paragraph:

function updateValue(e) {
  paragraph.textContent = e.target.value;
}

NOTE that the updateValue will be executed when you will type something in the textarea

You can check this for more information

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM