0

I'm trying to assign functionality to some buttons that have been added from an object. I'm hoping to have all the functions inside the object too but I'm not sure if this is possible.

The functions should fire when I click the buttons, but they're being called when I click the button that adds them.

I've tried assigning the buttons an ID each and then trying to add the event listener afterwards, but I get the same result, naming the functions and various other things, but nothing has helped.

var event = {
  TQ1: {
    title: "Title Here",
    body: "Lorem ipsum dolor sit",
    options: {
      opt1: {
        text: "Pick option 1",
        effect: function() {
          alert("Option 1 picked");
        }
      },
      opt2: {
        text: "Pick option 2",
        effect: function() {
          alert("Option 2 picked");
        }
      }
    }
  }
};

function newEvent() {
 
  $("#eventTitle").text(event.TQ1.title);
  $("#eventBody").text(event.TQ1.body);
  $("#eventOptions input").remove();
  addOptions(); //This is where the buttons are added.

  function addOptions() {
    var i;
    for (i in event.TQ1.options) {
      console.log(event.TQ1.options[i]);
      var newButton = $('<input/>').attr({
        id: i,
        type: "button",
        class: "btn btn-secondary optionButton",
        value: event.TQ1.options[i].text,
        onclick: event.TQ1.options[i].effect(),
      });
      $("#eventOptions").append(newButton);
      }
    }
  }

Thanks in advance for any help.

0 Answers0