Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

427
Visualizações
Why does the 'input' event not get fired when changing the value of an input field?

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" class="form__input" 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?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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" class="form__input" id="firstName">

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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda