Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

175
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda