0

I get troubles with theEventListeners if I use innerHTML+= to append a new input field, since there is a caching problem I guess.

<div id="frame">

  <input type="button"  id="btn"/>

</div>

JS

   document.getElementById("btn").addEventListener("click",function(){
       divframe.innerHTML+="  <input ... />..."
   });

I simply want if the user presses the button over and over again, there will be a new input and buttons.( with their own EventListeners <- unnecessary right now.)

3 Answers 3

2

Instead of ussing innerHTML use appendChild, so the first and the following buttons wont lose his event, and for the new elements you could add onclick event:

<div id="frame">
  <input type="button" value="Add" class="addBtn">
</div>
<script>function appendBtn(){
    var newBtn = document.createElement("input");
  newBtn.onclick = appendBtn;
  newBtn.value = "Add";
  newBtn.classname = "addBtn";
  newBtn.type = "button"
    document.getElementById("frame").appendChild(newBtn);
}

document.getElementsByClassName("addBtn")[0].addEventListener("click",function(){
    appendBtn()
})</script>
Sign up to request clarification or add additional context in comments.

1 Comment

You just taught me multiple things at once, please spend 20 seconds for structuring :))
1

You have to create element then append element into div. You can try this:

document.getElementById("btn").addEventListener("click", function() {  
  var div = document.getElementById("frame");   
  var input = document.createElement("INPUT");   
  div.appendChild(input); 
});

Hope this will help!

Comments

1

divframe.innerHTML+=... rewrites inner HTML and removes event listeners (if any) from child elements. You need to addEventListener again. Below is (useless but working) code. Note that only the first button remains clickable because getElementById returns only one (first) element with the same id. As it is said in other answers better use appendChild.

var divFrame=document.getElementById('frame');
function setListener(){
document.getElementById('btn').addEventListener('click',
function(){
divFrame.innerHTML+=divFrame.innerHTML;
setListener();
});
}
setListener();
<div id="frame">
<input type="button" id="btn" value="click" />
</div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.