2

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>

2 Answers 2

2

Rather than using setAttribute('onClick', consider assigning directly to the onclick property - that will allow you to use the b in that iteration in the handler's closure. There's also no need to create a global function, and you can simply assign to the id property of btn rather than using setAttribute:

data.contents.forEach(b => {
  const btn = document.createElement('input')
  btn.type = 'checkbox'
  btn.id = b.title;
  btn.onclick = () => {
    console.log(b.title);
    // do stuff with button and b
  };
  var t = document.createTextNode(b.title);  
  mydiv.appendChild(btn);
  mydiv.appendChild(t); 
});

If the only reason you were setting the ID was to be able to select it again with getElementById later, you can omit that entirely, due to the closure.

Sign up to request clarification or add additional context in comments.

Comments

0

Try this,

data.contents.forEach(b => {
const btn = document.createElement('input')
btn.type = 'checkbox'
btn.setAttribute("id",b.title);
btn.setAttribute("data",b.title);
btn.setAttribute("onClick","myFunction('"+b.title+"');");
var t = document.createTextNode(b.title);  
mydiv.appendChild(btn);
mydiv.appendChild(t); 
});

window.myFunction = function(id) {
var checkBox = document.getElementById(id);
console.log(id);
}

2 Comments

While this might answer the question, please explain why it does.
Okay, here we are passing argument(id) to the function and we can use this parameter inside the function.

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.