-1

I'm new in js .I'm dynamically adding new inputs and I want to get value from that input. How to add event listener for it?

  addNewInput(i) {
    const input = document.getElementsByClassName("scenario-inputs")
    let newInput = document.createElement("input")
    newInput.className = "dynamicInput"
    input[i].appendChild(newInput)
  }
Yerlan Yeszhanov
  • 2,149
  • 12
  • 37
  • 67
  • If you instead had a array of inputs that you push new input identifiers to and created components using something like map() you could much more easily keep track of each component as well as avoiding manual DOM manipulation. Manually adding elements is completely underutilizing React and components. – Alexander Staroselsky Mar 31 '19 at 13:43
  • addEventListener – Pranav C Balan Mar 31 '19 at 13:43
  • Possible duplicate of [add event listener on elements created dynamically](https://stackoverflow.com/questions/14258787/add-event-listener-on-elements-created-dynamically) – adiga Mar 31 '19 at 13:45
  • If you are adding the new inputs you can just add onChange hooks to it. But if they are being added by some third party library you will need to recur to some sort of refs – geckos Mar 31 '19 at 13:46

3 Answers3

1

You sort of answered your own question, every time you add your new input you just need to add a new event listener for it.

addNewInput(i) {
  const input = document.getElementsByClassName("scenario-inputs")
  let newInput = document.createElement("input")
  newInput.className = "dynamicInput"
  input[i].appendChild(newInput)
  newInput.addEventListener("keydown", function() {
      // do something ...
  }
}
peter
  • 538
  • 1
  • 3
  • 13
  • on "change" it doesn't work. It works on 'keydown'. What can be the porblem? – Yerlan Yeszhanov Mar 31 '19 at 13:59
  • Ah the change event "is not necessarily fired for each alteration to an element's value.", according to https://developer.mozilla.org/en-US/docs/Web/Events/change. So you can use 'keydown', or 'input' event handlers instead. – peter Mar 31 '19 at 14:05
0

If you are using react then that's a bad way to add elements dynamically. You can maintain an array which holds the information of each of the input elements and on addNewInput, just push a new entry to the array and react will render it for you.

varun agarwal
  • 1,491
  • 6
  • 9
0
addNewInput(i) {
  const input = document.getElementsByClassName("scenario-inputs")
  let newInput = document.createElement("input")
  newInput.className = "dynamicInput"
  input[i].appendChild(newInput)
  newInput.onchange = function () {to be implemented.}
}

It is enough to bind a listener. Whenever a change occurs in the input, your function is going to be invoked so that you can read the input's value.

Onur Arı
  • 502
  • 1
  • 4
  • 16