0

I am trying to dynamically create buttons which are displayed in the 5th (last) column of a table, which is also created dynamically. Everything is created properly. However, upon clicking the buttons, the function is not triggered. Perhaps it is because I am using vue.js to develop my front-end. I have tried using "v-on:click" instead of "click" in the button.setAttribute('click', 'claim()') code below, but this did not help.

  var table = document.createElement('table')
  for (var i = 1; i <= 5; i++) {
    var th = document.createElement('th')
    th.appendChild(header)
    table.appendChild(th)
  for (var j = 1; j <= 4; j++) {
    var tr = document.createElement('tr')
    for (var k = 1; k <= 5; k++) {
      var td = document.createElement('td')
      var node = document.createTextNode(k)
      td.appendChild(node)
      tr.appendChild(td)
      if (k === 5) {
        var button = document.createElement('input')
        button.setAttribute('type', 'submit')
        button.setAttribute('value', 'Purchase')
        button.setAttribute('click', 'purchase()')
        td.appendChild(button)
      }
    }
    table.appendChild(tr)
  }

1 Answer 1

1

You need to use addEventListener for adding any event. Example : button.addEventListener('click', purchase)

var app = document.getElementById("app");
var table = document.createElement('table');
app.appendChild(table)
for (var i = 1; i <= 5; i++) {
  var th = document.createElement('th')
  //th.appendChild(header)
  table.appendChild(th)
  for (var j = 1; j <= 4; j++) {
    var tr = document.createElement('tr')
    for (var k = 1; k <= 5; k++) {
      var td = document.createElement('td')
      var node = document.createTextNode(k)
      td.appendChild(node)
      tr.appendChild(td)
      if (k === 5) {
        var button = document.createElement('input')
        button.setAttribute('type', 'submit')
        button.setAttribute('value', 'Purchase')
        button.addEventListener('click', purchase)
        td.appendChild(button)
      }
    }
    table.appendChild(tr)
  }
}

function purchase() {
  console.log("done")
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id='app'>

</div>

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much tuhin47 for your time and answer. That works indeed!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.