" />
" />
"/>

Can't add onkeydown attribute to dynamically created input

44 Views Asked by At

HTML:

<form id="form">
  <div class="form-group" id="df2">
     <input type="text" class="form-control" name="atribut[]" onkeydown="changeIt(event)">
  </div>
  <div class="form-group" id="inputs">
  </div>
</form>

changeIt function:

<script>
let div = document.getElementById("df2");
let inputs = document.getElementById("inputs");
function changeIt(event) {
  var key = event.which || event.keyCode;
  if (key == '13') {
    const newInput = document.createElement('input');
    newInput.type = 'text';
    newInput.name = 'atribut[]';
    newInput.onkeydown = 'changeIt(event)';
    newInput.class = 'form-control';
    inputs.appendChild(newInput);
    console.log(newInput);
  }
}
</script>

And the console only showing type & name attributes of the new input. This is makes the new input can't produce new inputs again (it stops resulting only 2 inputs created, the original and the new one). How to resovle this?

2

There are 2 best solutions below

3
BoppreH On BEST ANSWER

When created via Javascript, the event listener must be a function, not a string. Use

// Good.
newInput.onkeydown = changeIt;

or

// Good.
newInput.onkeydown = event => changeIt(event);

or

// Good.
newInput.addEventListener('keydown', changeIt);

instead of

// Bad.
newInput.onkeydown = "changeIt(event)";
2
paliz On

here's change

 let div = document.getElementById("df2");
    let inputs = document.getElementById("inputs");
    function changeIt(event) {
        var key = event.which || event.keyCode;
        if (key == '13') {
            const newInput = document.createElement('input');
            newInput.type = 'text';
            newInput.name = 'atribut[]';
            //look here   
            newInput.addEventListener('keydown',changeIt);
             newInput.classList = 'form-control';
            inputs.appendChild(newInput);
        }
    }