skip to Main Content

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

Answers


  1. 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)";
    
    Login or Signup to reply.
  2. 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.class = 'form-control';
                inputs.appendChild(newInput);
            }
        }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search