简体   繁体   中英

How do I add a button to a td using js?

I have a table that is generated on the fly, as it is generating its TDs, I want to set the first TD to be a button. Below is my code, obviously doesn't work. I remember from another problem I had that we can change the content of a div using the .html(), but that doesnt work here neither.

Code:

    var table = document.getElementById("userinfo");
    var thead, tr, td;
    table.appendChild(thead = document.createElement("thead"));
    thead.appendChild(tr = document.createElement("tr"));
    tr.appendChild(td = document.createElement("td"));
    td.innerHTML = "Email";
    tr.appendChild(td = document.createElement("td"));
    td.innerHTML = "First Name";
    tr.appendChild(td = document.createElement("td"));
    td.innerHTML = "Last Name";
    tr.appendChild(td = document.createElement("td"));
    td.innerHTML = "Is Active?";

    for (var i in data)
    {
        tr = document.createElement("tr");
        tr.setAttribute("id", "row" + i);
        if (i%2 == 0)
        {
            tr.setAttribute("style", "background:white");
        }

        var entry = data[i];
        console.log(entry);
        table.appendChild(tr);
        tr.appendChild(td = document.createElement("td"));
        td.setAttribute("html", "<input type=\"button\" class=\"btn\" value=\'" + entry.email + "\" onclick=\"" + chooseUser(entry) + "\"/>");
        tr.appendChild(td = document.createElement("td"));
        td.innerHTML = entry.first_name;
        tr.appendChild(td = document.createElement("td"));
        td.innerHTML = entry.last_name;
        tr.appendChild(td = document.createElement("td"));
        td.innerHTML = entry.isActive;
    }

You can either use td.innerHTML = '<input type="button"...'; or you can do it the "proper" way:

var btn = document.createElement('input');
btn.type = "button";
btn.className = "btn";
btn.value = entry.email;
btn.onclick = (function(entry) {return function() {chooseUser(entry);}})(entry);
td.appendChild(btn);

This works for me.

 var row = {};
     var myTable = document.querySelector("table#tableProducts>tbody");

     row = myTable.insertRow();

     row.insertCell(-1).textContent = "dummy";
     var lastRow = row;
     var lastCell = lastRow.cells[lastRow.cells.length - 1];
     lastCell.innerHTML = "<button id='btnEdit';>Editar</button>";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM