9716278
9716278

Reputation: 2404

Why are my buttons not receiving their js loop created onclick command?

Please forgive my band HTML convention. I just have my tags like this for testing. I'm trying to have a that I function I can call on by my site, which will take a statically defined JSON variable, and pass it to a function that will create an HTML from the JSON. I coming into trouble when I'm not getting any errors, but I can't get by buttons to have their JSON defined onclick command. I've looked at the inspector after the pages have loaded and the JS has run, but the buttons don't have onclick attributes. I'm not getting any problems from the loop. The names for the buttons work fine. I'm stuck on getting the JS in the JSON to the buttons.

//Examle of mkmdl() input:
let inputVar = {
  'buttons': [{
      "button": "I'm a button",
      "command": "console.log('Im a command');"
    },
    {
      "button": "Me too",
      "command": "console.log('Me too');"
    }
  ],

  'message': "This here is our modle message.",

  'image': 'URL(image URL)'
}




function mkmdl(obj) {
  // this function makes model boxes from the supplied JSON object.

  //image

  //message

  //button(s)
  for (var i = 0, size = obj['buttons'].length; i < size; i++) {
    console.log(i);

    let v = obj["buttons"][i]["button"];
    let x = obj["buttons"][i]["command"];

    var newElement = document.createElement("button");

    newElement.onclick = x;

    newElement.innerHTML = v;


    document.getElementById("body").appendChild(newElement);

  }
}

window.onload = mkmdl(inputVar);
window.onload = function() {
  inputVar["buttons"][1]["command"]
};
<body id="body">

</body>

Upvotes: 0

Views: 37

Answers (1)

Jack Bashford
Jack Bashford

Reputation: 44087

It's because you're trying to assign an event listener with parameters in the handler. You can't do this. You should place each event handler in an anonymous function, and create functions from the strings using new Function:

//Examle of mkmdl() input:
let inputVar = {
  'buttons': [{
      "button": "I'm a button",
      "command": "console.log('Im a command');"
    },
    {
      "button": "Me too",
      "command": "console.log('Me too');"
    }
  ],

  'message': "This here is our modle message.",
  'image': 'URL(image URL)'
}


function mkmdl(obj) {
  // this function makes model boxes from suppiled JSON object.

  //image

  //message

  //button(s)
  for (var i = 0, size = obj['buttons'].length; i < size; i++) {
    console.log(i);

    let v = obj["buttons"][i]["button"];
    let x = new Function(obj["buttons"][i]["command"]);

    var newElement = document.createElement("button");
    newElement.onclick = () => x();
    newElement.innerHTML = v;

    document.getElementById("body").appendChild(newElement);
  }
}

window.onload = mkmdl(inputVar);
window.onload = function() {
  inputVar["buttons"][1]["command"]
};
<body id="body">

</body>

Upvotes: 1

Related Questions