0

I have a function that takes elements from an array, and uses javascript to format them for html, then passes them onto be appended. The elements include a form, which I want to process with ajax. Whilst with a regular form or with an onclick even everything works fine, if I try to include an event listener it won't work. Any ideas? Here below a simplified example:

    tempDiv.innerHTML = makeIt(i);//result is passed inside a loop, which does appendChild etc. 
                    //This all works fine, including when makeIt() specifies 'onclick' event handlers and/or a regular form with method="post". 
                    //However, I don't want the page to refresh, so I want to use ajax.
                
   function makeIt(var){
    res= 
     "<div>"+
      "<form id=\"myForm"+var+"\">"+
          "<textarea id=\"myText"+var+"\"></textarea>"+
          "<input type=\"submit\">"+
      "</form>"+
  "</div>"+
  "<script>"+
     "document.getElementById(\"myForm"+var+"\").addEventListener('submit', myFunction);"+
  "</script>";
    return(res);
   }

I tried simply replacing innerHTML with insertAdjacentHTML as suggested here, but it doesn't seem to work (the html doesn't show at all. If this truly is the solution, then I may just be doing something wrong in using it, and I will go back and try it more). I don't want to use jQuery, in order to keep the code light and simple.

Any ideas? Thanks in advance!

dan
  • 11
  • 2
  • event delegation is required here, because it's not possible to bind events to dynamically added elements (meaning, you can only use `addEventListener` on elements that were present in the DOM since the first page load) – GrafiCode Sep 17 '22 at 11:00
  • _"I may just be doing something wrong"_ obviously if _"the html doesn't show at all"_ is the actual result of calling `.insertAdjacentHTML()`. But we cannot help you with that because that's not part of your question. – Andreas Sep 17 '22 at 11:00
  • 1
    `var` is a reserved keyword hence `function makeIt(var){ ... }` should throw a syntax error. – Andreas Sep 17 '22 at 11:02
  • You can’t append scripts to existing dom elements by adding them in innerHtml. You could define the elements and event listeners with createElement and addEventListener. – James Sep 17 '22 at 11:06

0 Answers0