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

489
Visualizações
Uncaught ReferenceError: variable is not defined javascript

I want to create a DOM element from an HTML string. Inside that string, I have a button that should call a global function called downloadFile with predefined arguments.

My first try:

 <button onclick="downloadFile(${message_result})">Download</button>

But this failed to work.

Whole code looks like this

function downloadFile(result){
  console.log(result)
}

(() => {
  const msg = {user: 'User', message: 'Message', result: {}} // any

  var markup = `
  <h4>${msg.user}</h4>
  <p>${msg.message}</p>
  <button onclick="downloadFile(message_result)">Download</button>
  `

  document.body.innerHTML = markup
})()

the error: Uncaught ReferenceError: message_result is not defined at HTMLButtonElement.onclick

any suggestions how i can pass a variable into my function

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Let's first solve your problem then talk about a better approach.

If we assume msg.result is a string: You need to wrap it with quote marks.

<button onclick="downloadFile('${message_result}')">Download</button>`;

But if your msg.result is not a simple string or you want to take the right path to the solution, then we need to move next approach.

// This is your downloadFile function
const downloadFile = (data) => {
    console.log(data)
}

// This function creates download buttons
const createDownloadButton = (response) => {
  const markup = `
    <h4>${response.user}</h4>
    <p>${response.message}</p>
    <button>Download</button>
  `

  const container = document.createElement("div")
  container.innerHTML = markup;
  // Here, we assign "click" functionality dynamically even before we inject the element into DOM
  container.getElementsByTagName("button")[0].addEventListener('click', () => {
    downloadFile(response.result)
  })
  document.body.append(container)
}

// Fetch your response from an external service
const msg = {
  user: 'Username',
  message: 'Message',
  result: {
    file: {
      link: 'https://stackoverflow.com'
    }
  }
}

// Call function to create download button
createDownloadButton(msg)

about 4 years ago · Juan Pablo Isaza Relatório

0

If message_result is a variable, like msg.message, then you need to reference it similarly.

var markup=`
        <h4>${msg.user}</h4>
        <p>${msg.message}</p>
        <button onclick="downloadFile('${message_result}')">Download</button>`;
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