jeudi 2 août 2018

javascript checkbox event listener breaks if containing innerHTML is changed

I am trying to create checkboxes and insert a blank line after each one. When the checkbox is changed, I want to execute a function.

My code:

 <script>
  var div = document.getElementById("test");

  var cb1 = document.createElement('input');
  cb1.id = "cb_test1";
  cb1.type = "checkbox";
  cb1.defaultChecked = true;
  cb1.onchange = function(){alert("hi")};
  div.appendChild(cb1);

  div.innerHTML += "box1<br/>";

  var cb2 = document.createElement('input');
  cb2.id = "cb_test1";
  cb2.type = "checkbox";
  cb2.defaultChecked = true;
  cb2.onchange = function(){alert("hi")};
  div.appendChild(cb2);

  div.innerHTML += "box2<br/>";
</script>

The problem is, setting the innerHTML of the containing DIV seems to erase the event listener, so when the onchange event is fired, nothing happens.

How can I modify the innerHTML to add text and a new line without losing the event handler?

My actual code is much more dynamic and done in a loop, but the issue of the event handler getting dropped can be duplicated with the above code.




Aucun commentaire:

Enregistrer un commentaire