Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript insertAdjacentHTML a tag with an onclick event

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 class="icon-close"></i></a>`
      );
    }  else {
      console.log('remove')

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 class="icon-close"></i></a>`
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading