Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

170
Views
Insert long html code in javascript, but onclick doesn't works

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>
The problem is when I run click the 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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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();
}

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!