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

187
Visualizações
Why can't I update an input element inside click event?

Why does the input element not get updated?

function route() {
    let textfield = {
     inputEl: document.querySelector('#textfield'),
     setValue: function(str) {
        this.inputEl.value = str;
     }
   };

   textfield.inputEl.addEventListener('click', function(event) {
     document.body.innerHTML += '<button id="select">Select</button>';
     owner(textfield);
   });
}

function owner(controller) {
  document.querySelector('#select').addEventListener('click', function(event) {
      controller.setValue("Hello Universe!");
  });
}

route();

I know how to go around this problem but i prefer to use controller.setValue() to update the input.

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

0

UPDATED

I have updated the code below - hopefully this is closer to what you are trying to achieve.

I needed to add a container where to place the button (instead of adding it to the body) - so added a wrapper container like this:

<div id="container">
    <input type="text" id="textfield" />
</div>

Then, we can append the button to it as a child, like this:

document.getElementById('container').appendChild(btn);

See updated code below

function route() {
  let textfield = {
    inputEl: document.querySelector('#textfield'),
    setValue: function(str) {
      this.inputEl.value = str;
    }
  };

  textfield.inputEl.addEventListener('click', function(event) {
    // add the button if it's not already in there
    if(document.getElementById('select')){
      return;
    }
    
    let btn = document.createElement('button');
    btn.id = 'select';
    btn.innerHTML = 'Select';


    document.getElementById('container').appendChild(btn);
    owner(textfield);
  });
}

function owner(controller) {
  document.getElementById('select').addEventListener('click', function(event) {
    controller.setValue("Hello Universe!");
  });
}

route();
<div id="container">
  <input type="text" id="textfield" />
</div>

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