user12825970
user12825970

Reputation:

JS table generator with buttons

I found this answer on Stackoverflow and used it as a base for my own code which I will put below for you to check out.

I was just trying to get the buttons to render within the table but it just came up as plain text and not rendering as an HTML element on the page which is what I expected to happen with it.

Here's the code that was using here for a reference point:

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 btn = "<button>" + j +"-"+i+"</button>"
      var cellText = document.createTextNode(btn);

      cell.appendChild(cellText);
      row.appendChild(cell);
    }
    tblBody.appendChild(row);
  }
  tbl.appendChild(tblBody);
  body.appendChild(tbl);
  tbl.setAttribute("border", "2");
}

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

Does anyone know what solutions that you do to get it working the way I want it too? All help is appreciated.

Upvotes: 1

Views: 364

Answers (2)

Barmar
Barmar

Reputation: 781310

createTextNode() creates a text node, as the name says. If you have markup in it, it will be shown literally.

You should have created a button node, and set its text to the variables like this example below.

    for (var i = 0; i <10; i++) {
      var cell = document.createElement("td");
      var btn = document.createElement("button");
      btn.innerText = j + "-" + i;
      cell.appendChild(btn);
      row.appendChild(cell);
    }

Upvotes: 2

Hamza Arshad
Hamza Arshad

Reputation: 846

You need to create a button node and then append it.

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){
  msg('x:'+x+ ' y:'+y)
}

Upvotes: 0

Related Questions