3

I wanted to make simple to-do list app, i created function which gets value from input box and inside this function as wells creates checkbox near text, now i want to make function which will executes whenever checkbox is being clicked. Since checkbox is not on the page when documents load i'm getting error, how can i make it work properly?

Here is my code:

var btn = window.document.getElementById("btn");
var result = window.document.getElementById("result");

function getValue() {
  var input = window.document.getElementById("input").value;
  var checkbox = document.createElement('input');
  checkbox.type = 'checkbox';
  checkbox.className = 'checkbox';
  result.appendChild(checkbox);
  result.innerHTML += input + "<br>";

}

var checkbox = document.getElementById('checkbox');

btn.addEventListener('click', getValue);
checkbox.addEventListener('click', function(){
  alert("Clicked");
});
<input type="text" id="input">
<input type="button" value="Submit" id="btn">

<div id="result">

</div>
Andrew
  • 1,507
  • 1
  • 22
  • 42
  • i'm not sure if this will work because checkboxes only being created when i click button to add value from input to div – Andrew May 22 '18 at 18:52
  • This is pretty easily handled in jQuery, but I did find this vanilla js version of the same thing: https://gist.github.com/Daniel-Hug/abbded91dd55466e590b – dmgig May 22 '18 at 18:56
  • Thanks but i want to do it in pure js – Andrew May 22 '18 at 18:56

2 Answers2

0

This is how it's made.

You need to move the addEventListener after you create your checkbox.

Also, you need to use createTextNode since using innerHTML detaches your addEventListeners (1). For this same reason, you need to move appendChild to the bottom of the function.

var btn = window.document.getElementById("btn");
var result = window.document.getElementById("result");

function getValue() {
  var input = window.document.getElementById("input").value;
  var checkbox = document.createElement('input');
  checkbox.type = 'checkbox';
  checkbox.addEventListener('click', function(){
    alert("Clicked");
  });
  text = document.createTextNode(input);
  result.appendChild(checkbox);
  result.appendChild(text);
}

var checkbox = document.getElementById('checkbox');

btn.addEventListener('click', getValue);
<input type="text" id="input">
<input type="button" value="Submit" id="btn">

<div id="result">

</div>
Jorjon
  • 5,316
  • 1
  • 41
  • 58
0

Unfortunately I am not near my pc and cannot type you a code example. I assume that you would like the newly added checkbox to call a function when you click it? To do so, you will need to add an event listener to the new checkbox, after it is created. You can do this inside your function that creates the new checkbox (getValue).

If what I am saying is not clear, I will write you a code sample later.

Arnoux
  • 226
  • 2
  • 9