Sir Rubberduck
Sir Rubberduck

Reputation: 2262

addEventListener not working inside function

I am trying to generate a form based on these settings...

let formItems = new Form("form-items", {
        items: [
            { id: "companyName" },
            { id: "documentKey" },
            { id: "documentDate" }
        ],
    });

Inside, I generate each input, and try to add an eventListener, but it donesn't work. What am I doing wrong?

module.exports = function Form(formElementId, options) {

    this.state = {}

    options.items.map(item => {
        renderInput(item.id);
        this.state[item.id] = ""
    })

    function renderInput(id) {

        let html = `<input id="${id}" />`

        document.getElementById(formElementId).innerHTML += html;

        document.getElementById(id).addEventListener("input", (e) => {
            console.log(e);                      // <--------- Doesn't work
            this.state[id] = e.target.value;     // <--------- Doesn't work
            console.log(this.state);             // <--------- Doesn't work
        })
    }
}

Upvotes: 2

Views: 492

Answers (1)

ROOT
ROOT

Reputation: 11622

Instead of having your variable as template literal, you can just dynamically create an HTML input element and attach to it the event, also instead of add the HTML to using += just have appended to the container

I would use this snippet instead:

module.exports = function Form(formElementId, options) {
  this.state = {};
  self = this;
  options.items.map(item => {
    renderInput(item.id);
    this.state[item.id] = "";
  });

  function renderInput(id) {
    let input = document.createElement("input");
    input.setAttribute("id", id);

    document.getElementById(formElementId).append(input);

    input.addEventListener("input", e => {
      self.state[id] = e.target.value;
    });
  }
};

Upvotes: 3

Related Questions