Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

190
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda