0

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.

1
  • Can u share fiddle or snippet? Commented Dec 14, 2017 at 6:09

2 Answers 2

1

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);
};
Sign up to request clarification or add additional context in comments.

3 Comments

Is there anyway to set the background color of selected row?
Update my answer @hyperfkcb
Sorry but there is a slight problem because let's say the row is limited to single select. Is there anyway to clear the previous selected row before highlighting the new one?
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.