Home > Back-end >  Javascript insertAdjacentHTML a tag with an onclick event
Javascript insertAdjacentHTML a tag with an onclick event

Time:07-07

When a checkbox is checked I insert a new a tag to display what is selected. I add an onclick event to that a tag but when I cick on it for some reason it gives me an error that the function cannot be found.

const removeItem = (e) => {
  e.preventDefault();
  e.target.remove();
}
document.querySelectorAll('.choose').forEach(choose => {
  choose.addEventListener('change', (e) => {
    if (e.target.checked) {
      document.getElementById('selected').insertAdjacentHTML(
        "beforeend",
        `<a id="chosen-${e.target.id}" href="" onclick="removeItem()">${e.target.value}<i ></i></a>`
      );
    }  else {
      console.log('remove')

    }
      // document.getElementById('selected').querySelect('selectedItem').remove();
  })
})
<label>
 <input
  value="Value 1"
  id="1"
  
  type="checkbox"
  data-np-invisible="1"
  data-np-checked="0"
 /> 
Add Value 1
</label>
<div id="selected"></div>

CodePudding user response:

I tested it in the snippet and it looks like e is undefined. You need to pass event to the removeItem function here:

`<a id="chosen-${e.target.id}" href="" onclick="removeItem(event)">${e.target.value}<i ></i></a>`
  • Related