Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

173
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda