Adding button to dynamically generated HTML table - javascript

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.

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

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

Related

Delete a row from a table (HTML/JS)

Title is pretty self-explanatory; I'm trying to add a delete button to each row of a table, but right now it's deleting the table headers instead of the actual row. This is the Javascript; any tips?:
function addRow() {
var table = document.getElementById("todayTasks");
var row = document.createElement('tr');
row.id = "new_add";
var td0 = document.createElement("INPUT");
td0.type = "checkbox";
td0.id = "checkbox";
td0.onchange = updateItem;
var td1 = document.createElement('td');
var td2 = document.createElement('td');
var td3 = document.createElement("input");
td3.type = "button";
td3.value = "Delete";
td3.onclick = deleteFn;
if (document.getElementById('task').value === "") {
alert("Please provide a task.");
} else if (document.getElementById('duration').value === "") {
alert("Please provide a duration.");
} else {
td1.innerHTML = document.getElementById('task').value;
td2.innerHTML = document.getElementById('duration').value;
row.appendChild(td0);
row.appendChild(td1);
row.appendChild(td2);
row.appendChild(td3);
table.children[0].insertBefore(row, table.children[0].childNodes[1]);
}
function updateItem() //Cross out when checked
{
if (document.getElementById("checkbox").checked) {
document.getElementById("new_add").style.textDecoration = "line-through"
} else {
document.getElementById("new_add").style.textDecoration = "none"
}
}
function deleteFn(x) {
var i = x.rowIndex;
document.getElementById("todayTasks").deleteRow(i);
}
Your delete function take an event as an argument, that event hold a reference to the element via its property target. you can than get the tr which is the parent element of your input (if you wrap the input inside a td it would be the grand parent), then you can juste remove this element from the table
function deleteFn(event) {
var input = event.target;
var currentRow = input.parentNode;
document.getElementById("todayTasks").removeChild(currentRow);
}

How to get innerHTML of td in dynamically populated table in JavaScript

I created a table and populated values from an array, so I have 5x5 table, where each td will be filled with a word. The word come from array memo and all the code below works fine.
var myTableDiv = document.getElementById("results")
var table = document.createElement('TABLE')
var tableBody = document.createElement('TBODY')
table.border = '1'
table.appendChild(tableBody);
//TABLE ROWS
for (i = 0; i < this.memo.length; i++) {
var tr = document.createElement('TR');
for (j = 0; j < this.memo[i].length; j++) {
var td = document.createElement('TD');
td.onclick = function () {
check();
}
td.appendChild(document.createTextNode(this.memo[i][j]));
tr.appendChild(td)
}
tableBody.appendChild(tr);
}
myTableDiv.appendChild(table);
I have one question : I would like to click on the cell and get the word, which belongs to the cell.
For this purpose I tried onclick as I created td element
td.onclick = function () {
check();
}
The function check should print the innerHTML of the cell, which was clicked
function check() {
var a = td.innerHTML;
console.log(a);
}
But it gives me always wrong text - the last one in the array, which was populated.
How could I solve it?..
You always get the last td in the array because the last value that was set to td was of the last cell. You need to add the a parameter, say event, to onclick's callback function, and then your clicked element will be referenced in event.target. Then you would be able to get it's innerHTML.
Here's why it's always giving you the first element: after the for (j = 0; ... loop is finished, the variable td will hold the value of the last element in the list. Then, when check is called, it accesses that same td variable pointing to the last element.
To solve this, you can add an argument to the function to accept a specific element and log that.
td.onclick = function () {
check(td);
};
// later...
function check(element) {
var html = element.innerHTML;
console.log(html);
}
I would pass the innerHTML in the click itself - please see working example below, with some mock data for memo.
var myTableDiv = document.getElementById("results")
var table = document.createElement('TABLE')
var tableBody = document.createElement('TBODY')
var memo = [
['joe', 'tom', 'pete'],
['sara','lily', 'julia'],
['cody','timmy', 'john']
]
table.border = '1'
table.appendChild(tableBody);
//TABLE ROWS
for (i = 0; i < this.memo.length; i++) {
var tr = document.createElement('TR');
for (j = 0; j < this.memo[i].length; j++) {
var td = document.createElement('TD');
td.onclick = function () {
check(this.innerHTML);
}
td.appendChild(document.createTextNode(this.memo[i][j]));
tr.appendChild(td)
}
tableBody.appendChild(tr);
}
myTableDiv.appendChild(table);
function check(a) {
console.log(a);
}
<div id="results">
</div>
you can try..
td.onclick = function () {
check();
}
to
td.onclick = function (evt) {
var html = evt.target.innerHTML;
console.log(html);
check(html); //to do something..
}

how to set onclick attribute in a loop

I am building a table with text in the first column and buttons that do stuff in the second column. Here is the complete .js file:
var table = document.createElement("table");
var tableBody = document.createElement("tbody");
for(i = 0; i < array.length; i++) {
var row = table.insertRow(i);
var cell = row.insertCell(0);
cell.innerHTML = text[i];
var cell = row.insertCell(1);
var cellElement = document.createElement("input");
cellElement.setAttribute("id", ID[i]);
cellElement.setAttribute("type", "button");
cellElement.setAttribute("value", "button");
/////cellElement.onclick =
/////function(){ doThisThing(i,ID[i]); } );
cell.appendChild(cellElement);
row.appendChild(cell);
}
table.appendChild(tableBody);
document.body.appendChild(table);
Everything works except for the cellEllement.onclick = function(){}; The onlick() function does not set. I have tried variations on this:
cellElement.setAttribute("onclick",doThisThing(i,ID[i]));
How to I set the button onclick attribute when looping through to create a table?
You're using a reference to the i variable inside your function which will continue to change with the loop, and won't hold the value of i that it has when you go through that iteration of the loop. You need to hold on to the current value of i, probably by wrapping your callback in another function:
cellElement.onclick = (function(currI) {
return function() { doThisThing(currI, ID[currI]); };
})(i);
You could also use bind to make things simpler:
cellElement.onclick = doThisThing.bind(null, i, ID[i]);

Delete the row you click on (Javascript dynamic table)

I want to delete a row from a table, I am using Javascript.
I am dynamically creating table rows and in the last cell I have delete button so how to make it delete the row?
var newData4 = document.createElement('td');
var delButton = document.createElement('input');
delButton.setAttribute('type', 'button');
delButton.setAttribute('name', 'deleteButton');
delButton.setAttribute('value', 'Delete');
newData4.appendChild(delButton);
newRow.appendChild(newData4);
this is the function for creating my table rows
function addItem()
{
document.getElementById('add').onclick=function()
{
var myTable = document.getElementById('tbody');
var newRow = document.createElement('tr');
//var element1 = document.createElement("input");
//element1.type = "checkbox";
//newRow.appendChild(element1);
var newData1 = document.createElement('td');
newData1.innerHTML = document.getElementById('desc').value;
var newData2 = document.createElement('td');
newData2.innerHTML = document.getElementById('taskPriority').value;
var newData3 = document.createElement('td');
newData3.innerHTML = document.getElementById('taskDue').value;
myTable.appendChild(newRow);
newRow.appendChild(newData1);
newRow.appendChild(newData2);
newRow.appendChild(newData3);
var newData4 = document.createElement('td');
var delButton = document.createElement('input');
delButton.setAttribute('type', 'button');
delButton.setAttribute('name', 'deleteButton');
delButton.setAttribute('value', 'Delete');
newData4.appendChild(delButton);
newRow.appendChild(newData4);
}
}
function SomeDeleteRowFunction(btndel) {
if (typeof(btndel) == "object") {
$(btndel).closest("tr").remove();
} else {
return false;
}
}
try this code here is fiddle
alternatively try
//delete the table row
$(document).on('click', '#del', function(){
$(this).parents('tr').remove();
});
}); //del is the id of the delete block
one pure javascript approach
function deleteRowUI(btndel) {
var table=document.getElementById('filterTableBody');
if (typeof(btndel) == "object") {
p=btndel.parentNode.parentNode;
p.parentNode.removeChild(p);
var oTable = document.getElementById('filterTableBody');
//gets rows of table
var rowLength = oTable.rows.length;
for (var i = 1; i < rowLength; i++){
var oCells = oTable.rows.item(i).cells;
//gets cells of current row
var cellLength = oCells.length-1;
for(var j = 0; j < cellLength; j++){
oCells.item(j).innerHTML = "";
break;
}
break;
}
} else {
return false;
}
}
if you want to temporary hidden it you can do:
this.parentNode.style.display='none';
in mind that the exclusion button is in a td.
But if you want to really delete it from the html and the database:
you need to make the same as above and a extra call to a function of php/plsqlwathever to delete from de db, i recommend using ajax to call it.
http://www.w3schools.com/ajax/default.asp
uses jQuery remove method to do it.
By the id attribute :
$("#id here").remove();
By the class attribute :
$(".class name here").remove();
I hope I've helped a little...

Adding ledger totals in multiple TDs

This code generates a ledger. I narrowed it down to the minimum. By clicking a plus sign it adds an additional row to the ledger.
I'm looking to add each total of the variable newAmount and locate its updated total in a TD to the right of each row. I created newAmount.id = "mainAmount"; to create unique IDs thinking this would help.
var mainNumber = 0;
function addElement()
{
//add a number for each row
mainNumber++;
//create each row, id each slot, and add it where it goes
newDiv = document.createElement("div");
newDiv.id = "main";
newTable = document.createElement("table");
newTable.id = "mainTable";
newDiv.appendChild(newTable);
newTr = document.createElement("tr")
newTr.id = (mainNumber);
newTr.className = "mainRow";
newTable.appendChild(newTr);
newAmount = document.createElement("td");
newAmount.id = "mainAmount";
newAmount.className = (mainNumber);
newPlus = document.createElement("td");
newPlus.id = "mainPlus";
newTotalTable = document.createElement("table");
newDiv.appendChild(newTotalTable);
newTotalTable.id = "mainTotalTable";
newTotalTr = document.createElement("tr");
newTotalTable.appendChild(newTotalTr);
newTotalTr.id = "mainTotalTr";
newTotalTd = document.createElement("td");
newTotalTd.id = "mainTotalTd" + (mainNumber);
newTr.appendChild(newAmount);
newTotalTr.appendChild(newTotalTd);
//whats default inside of each slot
newAmount.innerHTML = '<form name="formAmount"><textarea name="textAmount" size="25" onfocus="wait();" id="amount' + (mainNumber) + '">0</textarea>';
newTr.appendChild(newPlus);
//click this to add a row
newPlus.innerHTML = '<img src="images/plus.png">';
// add the newly created element and it's content into the DOM
my_div = document.getElementById("mainAnchor");
document.body.insertBefore(newDiv, my_div);
}
//doesn't work...trying to hover over any row and show var idName in console
function trHover(){
$('tr').hover(function() {
var idName = $('tr'+'#'+(mainNumber)).attr('id');
console.log(idName);
});
}
//when you focus on amount box, this is activated, which adds attribute onblur and stars addTotal
function wait(){
var blurred = $(this).attr("onblur");
blurred = addTotal();
}
//adds total and displays it in td to the right
function addTotal(){
var y = 1;
var sum = 0;
var input;
while( ( input = document.getElementById( 'amount'+y ) ) ) {
sum += parseInt( input.value );
++y;
console.log(sum);
$("#mainTotalTd1").text(sum);
}
}
Rather than adding a single row, it looks like clicking the plus sign adds a div and two tables, so I'm not sure what you are going for there. I can fix the hover function, though:
$('tr').hover(function() {
var idName = $(this).attr('id'); // 'this' is the element being hovered
console.log(idName);
});

Categories

Resources