I have a task where I should be able to put any text in <textarea>
, then text will be immediately displayed in <p>
. I am trying to do it with addEventListener
that works fine with input field but for some reasons doesn't work for textarea.
let textArea = document.querySelector('.text-area')
let output = document.querySelector('.p-tag')
textArea.addEventListener('change', updateValue)
function updateValue(e){
output.textContent = e.target.value
}
I have a task where I should be able to put any text in <textarea>
, then text will be immediately displayed in <p>
. I am trying to do it with addEventListener
that works fine with input field but for some reasons doesn't work for textarea.
let textArea = document.querySelector('.text-area')
let output = document.querySelector('.p-tag')
textArea.addEventListener('change', updateValue)
function updateValue(e){
output.textContent = e.target.value
}
Share
Improve this question
asked Dec 21, 2020 at 18:15
JohnPixJohnPix
1,8531 gold badge26 silver badges55 bronze badges
4
- You can use the "onkeyup" event instead. – wawan Commented Dec 21, 2020 at 18:20
- so use a keyUp event listener instead – ControlAltDel Commented Dec 21, 2020 at 18:20
-
3
Use the
input
event instead ofkeyup
orchange
for better patibility with touch devices that don't have "keys". – Scott Marcus Commented Dec 21, 2020 at 18:27 - In what way does this work with an input field but not with a textarea? The behavior is identical with the code you provided. – Sebastian Simon Commented Dec 21, 2020 at 18:38
1 Answer
Reset to default 7Use the input
event instead:
Note: The
input
event is fired every time thevalue
of the element changes. This is unlike thechange
event, which only fires when the value is mitted, such as by pressing the enter key, selecting a value from a list of options, and the like.
From change
:
Depending on the kind of element being changed and the way the user interacts with the element, the
change
event fires at a different moment:
- […]
- When the element loses focus after its value was changed, but not mited (e.g., after editing the value of
<textarea>
or<input type="text">
).