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!