Home > database >  onchange element.appendChild again and again
onchange element.appendChild again and again

Time:07-16

<p >
  <form id="links">
    <input type="text"  name="input" onchange="createLink()">
    <br>
  </form>
</p>
</div>
<script>
 function createLink() {
   var newline = document.createElement("br");
   var input = document.createElement("input");
   input.type = "text";
   input.name = "input";
   input.onchange = "createLink()";
   var element = document.getElementById("links");
   element.appendChild(newline);
   element.appendChild(input);
 }

</script>



I tried to repeat create a new input field again from the new input field, but its only possible from my first input field. Why? And whats the best solution

CodePudding user response:

Use this code. I hope this code work you mean )

<p >
      <form id="links">
          <input type="text"  name="input" onchange="createLink()"><br>
      </form>
</p>

<script>
    var element = document.getElementById("links");
    
    function createLink(){
      var newline = document.createElement("br");
      var input = document.createElement("input");
      input.type = "text";
      input.name = "input";
      input.addEventListener('change', createLink)

      element.appendChild(newline);
      element.appendChild(input);
    }
</script>

CodePudding user response:

Your Implementation is a little bit off the mark.Instead of passing the createLink as string. pass it as arrow function, as shown below:

<p >
  <form id="links">
    <input type="text"  name="input" onchange="createLink()">
    <br>
  </form>
</p>
</div>
<script>
 function createLink() {
   var newline = document.createElement("br");
   var input = document.createElement("input");
   input.type = "text";
   input.name = "input";
   
   input.onchange = ()=> createLink();
   var element = document.getElementById("links");
   element.appendChild(newline);
   element.appendChild(input);
 }

</script>
  • Related