I need to create checkbox for each element in data.contents. So far I have created checkboxes using createElemnt(), set ID as their respective title and calling myFunction() during onClick. Now I am trying to retrieve ID when the checkbox is clicked using getElementbyID(b.title) and ended up with an error "b is not defined" which is obvious because I am trying to access b.title outside for loop.
I can't place myFunction() inside for loop because getElementById(b.title) is giving last checkbox's ID for all checkboxes if i do onClick which is also obvious because that's the last iteration's (b.title) of for loop.
My purpose is to retrieve ID(which was dynamically set inside for loop) of a checkbox during onClick from outside for loop. Any help would be much appreciated.
data.contents.forEach(b => {
const btn = document.createElement('input')
btn.type = 'checkbox'
btn.setAttribute("id", b.title)
btn.setAttribute("onClick", "myFunction();");
var t = document.createTextNode(b.title);
mydiv.appendChild(btn);
mydiv.appendChild(t);
});
window.myFunction = function() {
var checkBox = document.getElementById(b.title);
console.log(b.title)
}
HTML
<div id="mydiv">
</div>