How is using JS to change value of textarea different to user input?

Viewed 37

This is a little bit of a mystery to me but I'm sure someone with more JS knowhow will be able to clear this up. There is a large online forum site I use. Back in time I could easily change a comment-element (textarea) via JS, i.e.

document.querySelector("textarea").value = "foo"

then I'd click the save-button either by hand or script and it would save as you'd expect.

That site redesigned their whole front end a while back. When I do the exact same action now the change is not saved. The moment I activate the change action the original value is rendered.

My question is how do they do it? How do they differentiate if it was a user input or a script that changed the value?

  • The textarea DOM element is the only thing that changes
  • Nothing in the Redux happens differently
  • I tried dispatching a keydown but that did not do the trick either
  • Only if I actually click into the comment field and press a button the changes are saved correctly
1 Answers

Changing domElem.value doesn't trigger any events on the DOM element. If you want to simulate any event then you have to trigger the event manually through domElem.dispatchEvent.

for example: If you want to simulate keypress 'a' you have to write something like this.

document.querySelector("#name").value = 'a'
document.querySelector("#name").dispatchEvent(
  new KeyboardEvent('keypress', { key: 'a' })
)

// or if you want to trigger onchange event you have to do something like this.

document.querySelector("#name").dispatchEvent(
  new KeyboardEvent('change', { key: 'a' })
)
<input id="name" type="text" />

Related