I am using innerHTML to insert long html code to javascript.
Here is an example similar to my example:
let result = document.getElementById('result')
function display(){
result.innerHTML += '<input id="searchterm" type="text" /> <input id="search" type="button" value="Search" onclick="searchdata()"></input>'
function searchdata(){
console.log('it works')
}
}
<button onclick='display()'>Display</button>
<div id=result></div>
search button, it will display Uncaught ReferenceError: searchdata is not defined.
I know if I declare the function before I do the innerHTML statement, this will absolutely work.
However, I just wonder why does this happens?
Also, could someone provide me a better way to insert html in javascript because I want to insert a whole form in javascript(which is much more than I show in the example) and by using innerHTML, it is pretty hard to change and find bug later?
Thanks for any responds!
Updated: I know how to fix the problem, but I just looking for the reason and an advanced way of inserting html in javascript
Try moving "searchdata()" function out of the local scope and call it inside "display()" function. See if it works like this.
let result = document.getElementById('result')
function searchdata() {
console.log('it works')
}
function display() {
result.innerHTML += '<input id="searchterm" type="text" /> <input id="search" type="button" value="Search" onclick="searchdata()"></input>'
searchdata();
}