Home > Software engineering >  Why does the 'input' event not get fired when changing the value of an input field?
Why does the 'input' event not get fired when changing the value of an input field?

Time:01-02

Consider a minimal form such as the following:

let button = document.querySelector("button");
let firstNameInput = document.querySelector("#firstName");

firstNameInput.style.borderColor = "red";

button.addEventListener('click', () => {
  firstNameInput.value = "Goofy";
});

firstNameInput.addEventListener('input', () => {
  firstNameInput.style.borderColor = "black";
})
.form__input {
  border: none;
  outline: none;
  border-bottom: 1px solid black;
}
<form>
  <label for="firstName">Firstname:</label>
  <input type="text"  id="firstName">

  <button type="button">Button</button>
</form>

When loading this page, you should see an input field with a red bottom-border and next to it a button. If you click on the button, the name "Goofy" is written inside the input field. However, the bottom-border stays red. I would like it to change its color whenever something is written inside the input field. Now, when I go on and change the name manually, the border-color changes its color to black, just as I want. But can anyone explain to me why the border-color did not change when clicking on the button?

CodePudding user response:

The input event is an UI-Event, it's meant to fire when the user does action the page, not when scripts do.
For your case your script can simply call the same callback when it does set the .value.

let button = document.querySelector("button");
let firstNameInput = document.querySelector("#firstName");
const setBorderColor = () => {
  firstNameInput.style.borderColor = "black";
};
firstNameInput.style.borderColor = "red";

button.addEventListener('click', () => {
  firstNameInput.value = "Goofy";
  setBorderColor();
});

firstNameInput.addEventListener('input', setBorderColor)
.form__input {
  border: none;
  outline: none;
  border-bottom: 1px solid black;
}
<form>
  <label for="firstName">Firstname:</label>
  <input type="text"  id="firstName">

  <button type="button">Button</button>
</form>

  • Related