user12825970
user12825970

Reputation:

js button generator with functions

I got the code to generate the table with buttons i wanted, but i also want to get a "onlick="cell_id(" + j +"," + i ")" function within the <button> element using js.

The j and i variables are to mark the row and column where the click came from and also used to create the table.

the code:

function tableCreate() {
  var body = document.getElementsByTagName("body")[0];

  var tbl = document.createElement("table");
  var tblBody = document.createElement("tbody");

  for (var j = 0; j <= 10; j++) {
    var row = document.createElement("tr");

    for (var i = 0; i <10; i++) {
      var cell = document.createElement("td");
      var button = document.createElement("button");
      button.innerHTML = j +"-"+i;
      cell.appendChild(button);
      row.appendChild(cell);
    }
    tblBody.appendChild(row);
  }
  tbl.appendChild(tblBody);
  body.appendChild(tbl);
  tbl.setAttribute("border", "2");
}

function cell_id(x,y){
  window.alert('x:'+x+ ' y:'+y)
}

code from https://stackoverflow.com/a/61549235/12825970

Upvotes: 1

Views: 434

Answers (1)

Evan Trimboli
Evan Trimboli

Reputation: 30082

You can attach a listener to each button element:

function tableCreate() {
  var body = document.getElementsByTagName("body")[0];

  var tbl = document.createElement("table");
  var tblBody = document.createElement("tbody");

  for (var j = 0; j <= 10; j++) {
    var row = document.createElement("tr");

    for (var i = 0; i <10; i++) {
      var cell = document.createElement("td");
      var button = document.createElement("button");
      button.innerHTML = j +"-"+i;
      setupListener(button);
      cell.appendChild(button);
      row.appendChild(cell);
    }
    tblBody.appendChild(row);
  }
  tbl.appendChild(tblBody);
  body.appendChild(tbl);
  tbl.setAttribute("border", "2");
}

function setupListener(button, i, j) {
  button.addEventListener('click', () => {
    cell_id(button, i, j);
  });
}

function cell_id(button, x, y){
  msg('x:'+x+ ' y:'+y)
}

This approach works, but is expensive if you have a lot of buttons. For a more advanced approach, you can store the i and j as data attributes on the button, then use a single click event on the entire table. You can filter the events to check if they came from a "source" button. I'll leave that up to you if it's an option you want to pursue.

Upvotes: 1

Related Questions