QWERTY
QWERTY

Reputation: 2315

Adding button to dynamically generated HTML table

I am trying to add a button for each row of the dynamically generated HTML table using JavaScript. Here is my code:

// helper function        
function addCell(tr, text) {
    var td = tr.insertCell();
    td.innerHTML = text;
    return td;
}

// insert data
list.forEach(function (item) {
    var row = table.insertRow();
    var button = document.createElement('button'); 
    var bText = document.createTextNode('View'); 
    button.appendChild(bText); 
    addCell(row, item.itemName);
    addCell(row, '$ ' + item.total.toFixed(2));
    addCell(row, button);
});

I managed to print out all other fields except the button. The column for the button just simply printed out this:

[object HTMLButtonElement]

Just wondering if there is anyway to add a image button to the dynamically generated table? Upon selecting the button, I wanted to get the value of the row and pass as parameter to another function as well.

Upvotes: 0

Views: 1140

Answers (2)

Muhammet Can TONBUL
Muhammet Can TONBUL

Reputation: 3538

Here the fiddle. What you want i dont know. This way you can reach the line.

var previousitem=null;
function removeRowbyItem(item) {
      item.parentElement.parentElement.style.backgroundColor="red";
      if(previousitem!=null){
         previousitem.style.backgroundColor="";
         console.log(previousitem);
      }
    previousitem=item.parentElement.parentElement;
}
removeRow.innerHTML = "click me";
removeRow.onclick = function() {
  removeRowbyItem(this);
};

Upvotes: 1

Sreejesh K Nair
Sreejesh K Nair

Reputation: 603

You can use td.appendChild(button);

function addCell(tr, text) {
    var td = tr.insertCell();
    td.innerHTML = text;
    return td;
}
//for append button
function addButtonToCell(tr, button) {
    var td = tr.insertCell();
    td.appendChild(button);
    return td;
}
// insert data
list.forEach(function (item) {
    var row = table.insertRow();
    var button = document.createElement('button'); 
    var bText = document.createTextNode('View'); 
    button.appendChild(bText); 
    addCell(row, item.itemName);
    addCell(row, '$ ' + item.total.toFixed(2));
    addButtonToCell(row, button);
});

Upvotes: 0

Related Questions