insertRow JavaScript not recognized - javascript

I'm new to javascript but still tend to try fixing an issue myself. However, I got frustrated because the same function works for a slightly different HTML without tbody and thead.
The error I get is --> Uncaught TypeError: Cannot read property 'insertRow' of null.
Where am I wrong? Also probably there is a better way to add a table row? I tried .append but it did not work for me.
HTML
<table class="table table-striped myTable">
<button class="btn btn-primary btn-lg" id="addTableRow">Add table row</button>
<thead>
<tr>
<th>Name</th>
<th>Surname</th>
<th>Email</th>
<th>City</th>
<th>Sex</th>
<th>Date</th>
<th>Time</th>
</tr>
</thead>
<tbody>
<tr id="firstRow">
<td>John</td>
<td>Morgan</td>
<td>mail#mail.com</td>
<td>London</td>
<td>Male</td>
<td>09.12.14</td>
<td>04:17 a.m.</td>
</tr>
</tbody>
</table>
JavaScript
$("#addTableRow").click( function(){
var table = document.getElementById("myTable");
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
var cell5 = row.insertCell(4);
var cell6 = row.insertCell(5);
cell1.innerHTML = "Text-1";
cell2.innerHTML = "Text-2";
cell3.innerHTML = "Text-3";
cell4.innerHTML = "Text-4";
cell5.innerHTML = "Text-5";
cell6.innerHTML = "Text-6";
});

Just a few typos, missing ID on your table and mixing jQuery incorrectly.
$("#addTableRow").click( function () {
var row = $("<tr>");
row.append($("<td>Text-1</td>"))
.append($("<td>Text-2</td>"))
.append($("<td>Text-3</td>"))
.append($("<td>Text-4</td>"))
.append($("<td>Text-5</td>"))
.append($("<td>Text-6</td>"))
.append($("<td>Text-7</td>"));
$("#myTable tbody").append(row);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<table id="myTable" class="table table-striped myTable">
<button class="btn btn-primary btn-lg" id="addTableRow">Add table row</button>
<thead>
<tr>
<th>Name</th>
<th>Surname</th>
<th>Email</th>
<th>City</th>
<th>Sex</th>
<th>Date</th>
<th>Time</th>
</tr>
</thead>
<tbody>
<tr id="firstRow">
<td>John</td>
<td>Morgan</td>
<td>mail#mail.com</td>
<td>London</td>
<td>Male</td>
<td>09.12.14</td>
<td>04:17 a.m.</td>
</tr>
</tbody>
</table>

Not strictly related to the question, but I ended up here for having the "Uncaught TypeError: table.insertRow is not a function" error. You may be having the same problem. If so:
If you want to use
row.insertCell(0);
and you receive the former error, be sure not to get the element by using jquery:
DO NOT
let table = $("#peopleTable");
let newRow = table.insertRow(0);
DO
let table = document.getElementById("peopleTable");
let newRow = table.insertRow(0);

Related

adding bootstrap collapse to table cell with rowspan

I am creating a table using html, bootstrap and js.
I have used rowspan to get cells of different height.
The third cell in each row has more rows than the rest of the cells(hence the rowspan) (If this line is not clear please take a look at the jsfiddle)
Now each of the row in the third cell is a collapsible. So when I click on row it should open another table. (I have just made the first row collapsible for simplicity)
I have 2 issues:
1) The width of the cell increases when I click the collapsible element and decreases when I hide the collapsible element. I want the width to remain the same.
2) I want to make the hidden table start from the same place as the outer tables. It currently starts somewhere randomly on the page
$(document).ready(function() {
var list1 = {
"Feature": "TestSuite",
"Scenario": "TestName",
"Step": "line1<br>line2<br>line3<br>line4<br>",
"Result": "PASS"
}
var list2 = {
"Feature": "TestSuite1",
"Scenario": "TestName1",
"Step": "line1.1<br>line2.1<br>line3.1<br>line4.1<br>",
"Result": "PASS"
}
var dashboardMap = {
"TestSuite1": [list1, list2],
}
for (var key in dashboardMap) {
var resultsTable = dashboardMap[key];
for (var i in resultsTable) {
table = document.getElementById("resultsTable");
row = table.insertRow(-1);
cell1 = row.insertCell(0);
cell2 = row.insertCell(1);
cell3 = row.insertCell(2);
cell4 = row.insertCell(3);
cell1.innerHTML = "N/A";
cell2.innerHTML = resultsTable[i].Scenario;
var list = resultsTable[i].Step.split("<br>");
var rowspan = 0;
list.splice(-1, 1);
for (var step in list) {
rowspan++;
}
cell1.rowSpan = rowspan;
cell2.rowSpan = rowspan;
cell4.rowSpan = rowspan;
var hiddenTable = '<table> <tr> <th>Company</th> <th>Contact</th> <th>Country</th> </tr> <tr> <td>Alfreds</td> <td>Maria</td> <td>Germany</td> </tr> <tr>'
cell3.innerHTML = '<button type="button" class="btn btn-info" data-toggle="collapse" data-target="#demo">Simple collapsible</button><i id="demo" class="collapse"> ' + hiddenTable + ' </i>'
cell4.innerHTML = resultsTable[i].Result;
var k;
for (k = 1; k < list.length; k++) {
row = table.insertRow(-1);
cell1 = row.insertCell(0);
cell1.innerHTML = list[k];
}
}
}
});
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<div id="temp" class="container">
<div class="table-responsive">
<table class="table table-striped" id="resultsTable">
<thead>
<tr class="highlight-header" rowspan="3">
<th>header 1</th>
<th>header 2</th>
<th>header 3</th>
<th>header 4</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>

How to add data on selected cell rows in javascript?

I'm doing a web-based POS on PHP. There are two tables; the purpose of the first table is to fetch the products from search box from the database.If the products are available, I will mark the checkbox,click the 'Enter' Button and transfer it to the second table.I'd watch tutorials how to transfer row data from another table but my problem is I can only transfer the row in the first table and I want to add another data on cell because its lacking information.
I'll add picture of what I've done.
https://i.stack.imgur.com/rdSSf.png
function tab1_to_tab2()
{
var table1 = document.getElementById("table1"),
table2 = document.getElementById("table2"),
checkboxes = document.getElementsByName("tab1");
console.log("Val1 = " + checkboxes.length);
for(var i = 0; i < checkboxes.length; i++)
if (checkboxes[i].checked) {
var newRow = table2.insertRow(table2.length),
cell1 = newRow.insertCell(0),
cell2 = newRow.insertCell(1),
cell3 = newRow.insertCell(2),
cell4 = newRow.insertCell(3);
cell1.innerHTML = table1.rows[i+1].cells[0].innerHTML;
cell2.innerHTML = table1.rows[i+1].cells[1].innerHTML;
cell3.innerHTML = table1.rows[i+1].cells[2].innerHTML;
cell4.innerHTML = table1.rows[i+1].cells[3].innerHTML;
console.log(checkboxes.length);
}
}
I expect that column 'Qty','Subtotal' and 'Action' will be filled after I transfer rows from first table.
There are many ways. You can do like this also,
function add(){
$('input:checked[name=actionBox]').each(function() {
var product = $(this).attr('data-product');
var price = $(this).attr('data-price');
$('#bill').append("<tr><td>"+product+"</td><td>"+price+"</td><tr>");
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table border>
<tr>
<th>Item</th>
<th>Price</th>
<th>action</th>
</tr>
<tr>
<td>Sample product 1</td>
<td>200.00</td>
<td><input type='checkbox' name='actionBox' data-product='Sample product 1' data-price='200.00'>
</tr>
<tr>
<td>Sample product 1</td>
<td>200.00</td>
<td><input type='checkbox' name='actionBox' data-product='Sample product 2' data-price='300.00'>
</tr>
</table>
<br>
<button onclick='add()'>Enter</button>
<br><br>
<table border>
<tr>
<th>Description</th>
<th>Price</th>
</tr>
<tbody id='bill'>
</tbody>
</table>

Adding rows to table body dynamically

I am trying to add rows to an existing table that has header and footer also.
Here is my code:
<script>
function test() {
var tbl = document.getElementById("tbl");
var lastRow = tbl.rows.length - 1;
var cols = tbl.rows[lastRow].cells.length;
var row = tbl.insertRow(-1);
for (var i = 0; i < cols; i++) {
row.insertCell();
}
}
</script>
<table id="tbl" onclick="test()">
<thead>
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
</thead>
<tfoot>
<tr>
<td>Sum</td>
<td>$180</td>
</tr>
</tfoot>
<tbody>
<tr>
<td>January</td>
<td>$100</td>
</tr>
<tr>
<td>February</td>
<td>$80</td>
</tr>
</tbody>
</table>
when I click on any table I want to add new row to table body, but the issue here is the new row is added to table footer. please help me how to fix this issue.
You insert the row into the tBody element. Since there can be more than one tBody, you should refer to the tBodies prop of table at index 0.
var row = tbl.tBodies[0].insertRow(-1);
function test() {
var tbl = document.getElementById("tbl");
var lastRow = tbl.rows.length - 1;
var cols = tbl.rows[lastRow].cells.length;
var row = tbl.tBodies[0].insertRow(-1);
for (var i = 0; i < cols; i++) {
row.insertCell().appendChild(document.createTextNode(i));
}
}
test();
<table id="tbl" onclick="test()">
<thead>
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
</thead>
<tfoot>
<tr>
<td>Sum</td>
<td>$180</td>
</tr>
</tfoot>
<tbody>
<tr>
<td>January</td>
<td>$100</td>
</tr>
<tr>
<td>February</td>
<td>$80</td>
</tr>
</tbody>
</table>
Try something like this. Just clone first row and then append it as child to your table. Hope it will help you
function appendRow() {
let tbl = document.getElementById("tbl");
let newRow = tbl.rows[0].cloneNode(true);
tbl.appendChild(newRow);

How to find the corresponding th to a given td?

Basically the same question as How can I get the corresponding table header (th) from a table cell (td)? but not jQuery specific.
From a given <td> is there an easy way to find the corresponding <th>?
<table width="100%" id="stock">
<tr>
<th>Name</th>
<th>Type</th>
<th>Quantity</th>
<th>Options</th>
</tr>
<tr>
<td>foo</td>
<td id="target">bar</td>
<td>-1</td>
<td>...</td>
</tr>
I'd like something doing this:
document.getElementById('target').correspondingTH // would return HTMLObject <th>Type</th>
An ideal answer might contain both a jQuery way to do it and a vanilla one but I'm personally looking for a vanilla one.
Pure JavaScript's answer.
var index = Array.prototype.indexOf.call(your_td.parentNode.children, your_td)
var corresponding_th = document.querySelector('#your_table_id th:nth-child(' + (index+1) + ')')
As posted here in the more jQuery specifc question: https://stackoverflow.com/a/37312707/1524913
HTML table model gives easier solution. jquery in this case is more sophisticated. I tested following table:
<table style="width:100%" id="stock">
<tbody>
<tr>
<td>foo</td>
<td id="target">bar</td>
<td>-1</td>
<td>...</td>
</tr>
<tr>
<td>foo</td>
<td id="target">bar</td>
<td>-1</td>
<td>...</td>
</tr>
</tbody>
<tr>
<td>foo</td>
<td id="target">bar</td>
<td colspan="2">-1</td>
<!--<td>...</td>-->
</tr>
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th>Quantity</th>
<th>Options</th>
</tr>
</thead>
</table>
Script without jquery is simple and straightforward.
window.onload = function () {
var tbl = document.getElementById('stock');
var tds = document.getElementsByTagName('td');
for (var i = 0, td; td = tds[i]; ++i) {
td.onclick = function () {
var tr = this.parentNode;
console.log(tbl.rows[0].cells[this.cellIndex].innerHTML);
}
}
}
jquery also is useful.
$(document).ready(function () {
$('#stock td').click(function () {
console.log($(this).parents('table').find('tr:first-child').children('th:nth-child(' + (this.cellIndex + 1) + ')').html());
});
});
<thead> can be placed at the top, at the bottom, and between rows. thead inside tbody is obvious error but browser fixes it. Scripts work in any case.
I think you need to step through the TH colSpans to exactly match the TD
Try
function getHeadCell(td) {
var index = Array.prototype.indexOf.call(td.parentNode.children, td);
var table = td;
while (table && table.tagName != 'TABLE') table = table.parentNode;
var cx = 0;
for (var c = 0; cx <= index; c++) cx += table.rows[0].cells[c].colSpan;
return table.rows[0].cells[c - 1];
}
See https://jsfiddle.net/Abeeee/upt75s2x/34/ for a working example

How to include multiple td into the tr?

I just wanted to append td in the tr
Table
<table class="u-full-width" id="result">
<thead>
<tr>
<th>Project Name</th>
<th>Id</th>
<th>Event</th>
</tr>
</thead>
<tbody>
<tr>
<td>Dave Gamache</td>
<td>26</td>
<td>Male</td>
</tr>
</tbody>
</table>
Script
// Receive Message
socket.on('message', function(data){
console.log(data);
var Project = data.project;
var Id = data.id;
var Event = data.event;
var tr = document.createElement("tr");
var td1 = tr.appendChild(document.createElement('td'));
var td2 = tr.appendChild(document.createElement('td'));
var td3 = tr.appendChild(document.createElement('td'));
td1.innerHTML = Project;
td2.innerHTML = Id;
td3.innerHTML = Event;
document.getElementById("result").appendChild(td1, td2, td3);
});
I come up with this above code but this is not working means see the image...
The last line is wrong. You should append the tr to the table, not all the tds.
document.getElementById("result").appendChild(tr);
document.getElementById("result").appendChild(td1, td2, td3);
seems you are appending your tds directly to the table, not a tr in the tbody.
Try this way to bind your data
<table class="u-full-width" id="result">
<thead>
<tr>
<th>Project Name</th>
<th>Id</th>
<th>Event</th>
</tr>
</thead>
<tbody id="bodytable">
</tbody>
</table>
socket.on('message', function(data){
console.log(data);
var _html='';
html +='<tr>'
html +='<td>'+data.project+'</td>';
html +='<td>'+data.id+'</td>';
html +='<td>'+data.event+'</td></tr>';
$('#bodytable').append(_html);
});

Categories

Resources