Home > Back-end >  Why can't I update an input element inside click event?
Why can't I update an input element inside click event?

Time:05-20

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.

CodePudding user response:

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>

  • Related