admin 管理员组文章数量: 1086019
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">
).
本文标签: javascriptChange event for textareaStack Overflow
版权声明:本文标题:javascript - Change event for textarea - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://roclinux.cn/p/1744069842a2528284.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论