-1

My website receives some text through API call and that value is displayed on textarea on the page. I want to run a function to perform some tasks after the value is set to textarea. But I don't see any event triggering when setting textarea value through program. I cannot find any related questions, solutions or articles regarding this.

Below is the demonstration of the problem I am facing.

txt.onchange = () => {
  alert("textarea changed (onchange event)");
}

txt.onkeyup = () => {
  alert("textarea changed (onkeyup event)");
}

txt.onkeydown = () => {
  alert("textarea changed (onkeydown event)");
}

txt.oninput = () => {
  alert("textarea changed (oninput event)");
}

changetxt.onclick = () => {
  txt.value = "value is set programmetically.";
}
<textarea id="txt" rows="10"></textarea>
<button id="changetxt">Update Textarea</button>

I want some way to detect textarea value is changed through program.

Bibek Oli
  • 366
  • 2
  • 14

2 Answers2

1

If I'm understanding your problem correctly would this achieve the desired result

const { get, set } = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value');
const t = document.getElementById('txt');
Object.defineProperty(t, 'value', {
  get() {
    return get.call(this);
  },
  set(newVal) {
    console.log('Input changed');
    let result = set.call(this, newVal);
    return result;
  }
});

This is a modified version of https://stackoverflow.com/a/55033939/5072590

Amer M.
  • 68
  • 7
  • This is the only answer that actually solves the problem. – Michael M. Oct 22 '22 at 19:41
  • 1
    Many many thanks! Searching around the whole day for this solution. I found a few other examples with Object.defineProperty for value, but then the user input did not reflect anymore to value (get). Also maybe a hint, if your code is doing somting witht the textarea.value then take care on the order: ` set(newVal) { let result = set.call(this, newVal); //call function which refers to t.value.... return result; }` – HaPi Mar 17 '23 at 17:41
-1

is you js inside a fn that got triggered when the dom is ready? like described here? Vanilla JavaScript equivalent of jQuery's $.ready() - how to call a function when the page/DOM is ready for it

Marco
  • 473
  • 5
  • 21
  • This does not answer the question. OP wants to run code when the ` – Michael M. Oct 22 '22 at 15:51
  • ut the hooks works only when dom is ready – Marco Oct 22 '22 at 16:27
  • The problem is not that the JS is being before the DOM is ready. The problem is that event listeners are not called when code is changed programmatically. You have a fundamental misunderstanding. – Michael M. Oct 22 '22 at 16:31
  • code changed? i understood that the CONTENT of the textarea changed - so dom elements didn’t changed - lets see what the author thinks about the answers – Marco Oct 22 '22 at 18:04