Search code examples
javascripthtmltemplate-literals

Problem with Template Literal Function Passing


Quick Summary. I created a JSON file that holds some data (this is okay and is being displayed fine), from this I created a JavaScript function to export said JSON data to HTML (also fine).

The problem comes with the onclick function I added to each of the divs created from the below function, I am able to pass and log a number but for some reason, it's not working for a string.

function returnHTML() {
  // HTML Element to append JSON info to
  var div = document.getElementById('list');

  // Variable to test onClick
  var test = "TEST";

  fetch("./test.json")
  .then(function(res) {
    return res.json();
  })
  .then(function(data) {
    for (var i = 0; i < (data.games.fps).length; i++) {

      var markup = `
        <div class='box' id="${data.games.fps[i].name}" onclick="myFunction(${test})">
          <div class='box__top'> ${data.games.fps[i].img} </div>
          <div class='box__bottom'> ${data.games.fps[i].name} </div>
        </div>
      `;

      div.innerHTML = div.innerHTML + markup;
    }
  })
}

// Random function to test variable passing.
function myFunction(x) {
  console.log("Clicked: " + x);
}

returnHTML();

I expected the output via the console to be:

Clicked: TEST

However, I get: ReferenceError: Can't find variable: TEST


Solution

  • Your code is outputting onclick="myFunction(TEST)" because that's the value of the test variable when you're generating the HTML.

    Add double (or single) quotes and that should fix it:

    <div class='box' id="${data.games.fps[i].name}" onclick="myFunction('${test}')">