0

So I made a small version of my problem. Here I am adding text into an input element. But when it is added it doesnt trigger the event listener.

function testFunction() {
  document.getElementById("testInput").addEventListener("change", () => {
    console.log("hi");
  });
}

function testText() {
  document.getElementById("testInput").value = "Hello there";
}

testFunction();
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="styles.css" />
    <title>Document</title>
  </head>
  <body>
    <script></script>
    <button onclick="testText()" style="height: 20px"></button>
    <input id="testInput" />
    <script src="script.js"></script>
  </body>
</html>
pilchard
  • 12,414
  • 5
  • 11
  • 23
Shadow
  • 3
  • 3
  • just use `input` event instead of `change` – Mohit Sharma Jun 23 '22 at 11:35
  • the [change event](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/change_event) fires when the input loses focus, whereas the [input event](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event) fires on every change of value of the input. – pilchard Jun 23 '22 at 11:40
  • Does this answer your question? [Difference between "change" and "input" event for an \`input\` element](https://stackoverflow.com/questions/17047497/difference-between-change-and-input-event-for-an-input-element) – pilchard Jun 23 '22 at 11:40
  • it doesnt work with input instead of change either – Shadow Jun 23 '22 at 11:48

1 Answers1

0

You need to create the event manually and use dispatchEvent() method to fire the event to the target element.

function testFunction() {
  document.getElementById("testInput").addEventListener("input", () => {
    console.log("hi");
  });
}

function testText() {
  document.getElementById("testInput").value = "Hello there";

  let event = new Event("input");
  document.getElementById("testInput").dispatchEvent(event);
}

testFunction();
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="styles.css" />
    <title>Document</title>
  </head>
  <body>
    <script></script>
    <button onclick="testText()" style="height: 20px"></button>
    <input id="testInput" />
    <script src="script.js"></script>
  </body>
</html>
TechySharnav
  • 4,869
  • 2
  • 11
  • 29