I am creating an app that has multiple tables, one has the customer and their location, while another has the customer with their inventory items and item IDs. I am having trouble creating a function that can be used for multiple tables, the function allows the user to create new rows for a table, and I have working code, but with that code I have to copy it for each unique table.
What I want is to use (this) so that one single function will work for multiple tables, I have attempted using (this) but it obviously failed to work, the first problem is that it cannot read the property 'length' for the table, but I am sure I will run into many more problems.
Any help would be appreciated.
Desired Outcome: use (this) to use one single function on multiple tables.
function appendRow() {
var table = document.getElementsByTagName('table'); // table reference
length = this.length,
row = this.insertRow(this.rows.length), // append table row
i;
// insert table cells to the new row
for (i = 0; i < this.rows[0].cells.length; i++) {
createCell(row.insertCell(i), i, 'row');
}
}
// this works, but if I want it for multiple tables, I must copy it for each table....
/*
function appendRow() {
var custList = document.getElementById('custList'), // table reference
row = custList.insertRow(custList.rows.length), // append table row
i;
// insert table cells to the new row
for (i = 0; i < custList.rows[0].cells.length; i++) {
createCell(row.insertCell(i), i, 'row');
}
}
*/
function createCell(cell, text, style) {
var div = document.createElement('div'), // create DIV element
txt = document.createTextNode('_'); // create text node
div.appendChild(txt); // append text node to the DIV
div.setAttribute('id', style); // set DIV class attribute
div.setAttribute('idName', style); // set DIV class attribute for IE (?!)
cell.appendChild(div); // append DIV to the table cell
}
<div id="custDiv">
<div class="addBtns">
<input id="searchName" onkeyup="custSearchName()" type="text" placeholder="search name"></input>
</div>
<div style="width: 355px; margin: 0 auto; height: 50px;">
<button id="addCust" onclick="appendRow(this)">add customer</button>
</div>
<div class="custScroll">
<table id="custListTop" contenteditable="false">
<tr>
<td style="border-top-left-radius: 5px;">Customers</td>
<td style="border-top-right-radius: 5px;">Main Location</td>
</tr>
</table>
<table id="custList" contenteditable="true">
<tr>
<td>Someone</td>
<td>something</td>
</tr>
</table>
</div>
</div>