Skip to content
Advertisement

Adding Buttons to a Table created dynamically in vue.js

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)
  }

Advertisement

Answer

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>
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement