最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Change event for textarea - Stack Overflow

programmeradmin2浏览0评论

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 of keyup or change 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
Add a ment  | 

1 Answer 1

Reset to default 7

Use the input event instead:

Note: The input event is fired every time the value of the element changes. This is unlike the change 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">).
发布评论

评论列表(0)

  1. 暂无评论