du7ri
du7ri

Reputation: 342

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

Upvotes: 0

Views: 442

Answers (2)

Ahmet Can G&#252;ven
Ahmet Can G&#252;ven

Reputation: 5462

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)

Upvotes: 1

mykaf
mykaf

Reputation: 1389

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>`;

Upvotes: 0

Related Questions