How to check a table is empty or not using javascript - javascript

So i have a script like this to make a 2x2 table by javascript
function createtable(){
var tbl = document.getElementById('x');
if (tbl.contains()==false){
tbl.setAttribute('border', '1');
var tbdy = document.createElement('tbody');
for (var i = 0; i < 2; i++) {
var tr = document.createElement('tr');
for (var j = 0; j < 2; j++) {
var td = document.createElement('td');
tr.appendChild(td);
td.style.height='50px';
td.style.width='50px';
}
tbdy.appendChild(tr);
}
tbl.appendChild(tbdy);
}
<form>
<input type="button" value="Create Table" onclick="createtable()"> <br>
</form>
<table id="x"> </table>
I want to check if table x contains anything or not to create itself. Im trying to use the contains() to check but it doesnt work.

You can check the number of rows in the table:
var x = document.getElementById("myTable").rows.length;
See reference here: https://www.w3schools.com/jsref/coll_table_rows.asp
Using this:
var tbl = document.getElementById('x');
if (tbl.rows.length == 0) {
// empty
}

If you want to check if there are any inside table do this
document.getElementById("myTable").rows.length
More info here

you can Check the Row Counts
var tbl = document.getElementById('x');
if(tbl.rows.length==0){
}
if the tbl.rows.length is 0 that means the table don't have any rows

There are multiple ways. One of way, you can use childElementCount property.
if (tbl.childElementCount==0)
{
}
For more details you can refere link

In this case, since there are no child elements or text nodes in your table, you can just check to see if the innerHTML property is falsy. This prevents your createtable function from appending additional children after the function has been run once. For example:
function createtable() {
var tbl = document.getElementById('x');
if (!tbl.innerHTML) {
var tbdy = document.createElement('tbody');
tbl.setAttribute('border', '1');
for (var i = 0; i < 2; i++) {
var tr = document.createElement('tr');
for (var j = 0; j < 2; j++) {
var td = document.createElement('td');
tr.appendChild(td);
td.style.height = '50px';
td.style.width = '50px';
}
tbdy.appendChild(tr);
}
tbl.appendChild(tbdy);
}
}
<form>
<input type="button" value="Create Table" onclick="createtable()">
<br>
</form>
<table id="x"></table>

Plain javascript:
!![].length
or use Lodash
_.head([]);
// => undefined

Related

can't use If - Else element exists in Javascript

I wrote a JS function to create a table in html and JS I want to click submit and after that the table to be created but I dont want the Submit button to create another table if clicked again
I tried to use IF - Else statements in the function but It's not working
code:
Button:
document.getElementById("btn_submit").addEventListener("click",sizeGrid)
function
function makeGrid(x,y) {
event.preventDefault();
if (document.getElementById('tbl') != null)
{
return;
}
else
{
var body = document.getElementById('pixelCanvas');
var tbl = document.createElement('table');
for(var i = 0; i < x; i++){
var tr = tbl.insertRow();
for(var j = 0; j<y; j++){
var td= tr.insertCell()
}
}
body.append(tbl);
paint()
}
}
HTML
<h2>Design Canvas</h2>
<table id="pixelCanvas">
</table>
The table gets created two times after I click submit two times
You should set the tbl's id to 'tbl' by tbl.id = 'tbl'.
You are doing the check on the id of the table but never assign one.
function makeGrid(x,y) {
event.preventDefault();
if (document.getElementById('tbl') != null) {
return;
} else {
var body = document.getElementById('pixelCanvas');
var tbl = document.createElement('table');
tbl.id = "tbl"; // Assign the id for the check
for(var i = 0; i < x; i++){
var tr = tbl.insertRow();
for(var j = 0; j<y; j++){
var td= tr.insertCell()
}
}
body.append(tbl);
paint();
}
};

How to remove last row in table and set it as first row in javascript?

I have tried following function downward() for removing last row and insert it as first row whereas display() function just creates the table.
<body>
<script>
function downward() {
var table = document.getElementsByTagName('table');
var count = table.rows.length - 1;
var table = table[count];
var rows = table.getElementsByTagName('tr');
var shifted = rows[count];
rows[count].parentNode.removeChild(rows[count]);
table.insertBefore(rows[0]);
}
function display() {
var table = document.createElement('table');
table.setAttribute("id", "tbl");
for (var i = 0; i < 4; i++) {
var tr = document.createElement('tr');
for (var j = 0; j < 4; j++) {
var td = document.createElement('td');
var text = document.createTextNode(j+i);
td.appendChild(text);
tr.appendChild(td);
}
table.appendChild(tr);
}
document.body.appendChild(table);
}
</script>
<input id="display" type="button" value="Display" onclick="display();" />
<input id="downward" type="button" value="downward" onclick="downward();" />
</body>
Use .removeChild to remove the last child and insert it before the first element using .insertBefore. See example:
function myFunction(){
var table = document.getElementById("myTable");
var tr = document.getElementById("myTable").lastChild;
table.removeChild[document.getElementsByTagName("tr").lenght];
table.insertBefore(tr, document.getElementById("myTable").firstChild);
}
<table><tbody id="myTable"><tr><td>1</td></tr><tr><td>2</td></tr><tr><td>3</td></tr></tbody></table>
<br>
<button onclick="myFunction()" value="click me to see the result">click me to see the result</button>

Create table column-headers dynamically

Right now I cannot figure out how to add headers for all the columns in this code where a html-table are created dynamically
function createTableAndInsert(sqlArray) {
//create table dynamically - only one row by the moment
var table = document.createElement('table');
for (var i = 1; i < 2; i++) {
var tr = document.createElement('tr'); // row
for (var j = 0; j < 8; j++) {
var td = document.createElement('td'); //column
var text = document.createTextNode(sqlArray[j]); //cell
td.appendChild(text);
tr.appendChild(td);
}
table.appendChild(tr);
}
document.getElementById('single_fine_view').appendChild(table);
}
You can pass the header list separately to your function and add following code
function createTableAndInsert(sqlArray,headerList) {
var table = document.createElement('table');
var tr = document.createElement('tr'); // Header row
for (var j = 0; j < 8; j++) {
var th = document.createElement('th'); //column
var text = document.createTextNode(headerList[j]); //cell
th.appendChild(text);
tr.appendChild(th);
}
table.appendChild(tr);
for (var i = 1; i < 2; i++) {
var tr = document.createElement('tr'); // row
for (var j = 0; j < 8; j++) {
var td = document.createElement('td'); //column
var text = document.createTextNode(sqlArray[j]); //cell
td.appendChild(text);
tr.appendChild(td);
}
table.appendChild(tr);
}
document.getElementById('single_fine_view').appendChild(table);
}
Your structure is:
<tr>
<td>
<div></div>
<div></div>
</td>
</tr>
thead should be appended before each row.
<thead></thead>
<tr>
<td>
<div></div>
<div></div>
</td>
</tr>
Solution:
var thead = document.createElement('thead');
thead.innerHTML = 'Header';
Before table.appendChild(tr);, add this line table.appendChild(thead);
THEAD needs one or more TR elements:
var table = document.createElement('table'); // 'table' may be a reserved word
var tblHead = document.createElement('thead');
var rowHead = document.createElement('tr');
table.appendChild(tblHead);
tblHead.appendChild(rowHead)
for(j=0; j<8; j++) {
var celHead = document.createElement('th');
//the array txtHeaders[] should be passed to your function if you have the values in advance
// otherwise, you can access the header cells later by:
// table.getElementsbyTagName('th')[].innerHTML
celHead.innerHTML = txtHeaders[j]
rowHead.appendChild(celHead)
}
// now do your row & table loops

rowIndex when creating a table with Javascript

I have the following function to append rows and cells to an empty table:
function createTable(size) {
var table = document.getElementById("gameTable");
for (var i=0; i<size; i++) {
var tr = document.createElement("tr");
for (var j=0; j<size; j++) {
var td = document.createElement("td");
tr.appendChild(td);
}
table.appendChild(tr);
tr.rowIndex = i;
}
}
So far so good.
My problem is that later, when I tried to reach specific cells inside the table:
var x = target.parentNode.rowIndex;
var y = target.cellIndex;
table.rows[x].cells[y].innerHTML = 'blah'
target is the specific TD that was clicked.
the rows[x] index is always -1. Every time I try the line above I get an error: "cannot read property 'cells' of undefined"
I even tried manually setting the rowIndex of each Row to what it should be (inside the function), but to no avail.
The cellIndex comes out fine, but the rowIndex is -1 and each and every one of the newly created table rows.
What can I do to correct this?
This can be solved by appending the <tr> elements into a <tbody>.
function createTable(size) {
var table = document.getElementById("gameTable");
var tb = document.createElement("tbody");
for (var i=0; i<size; i++) {
var tr = document.createElement("tr");
for (var j=0; j<size; j++) {
var td = document.createElement("td");
tr.appendChild(td);
}
tb.appendChild(tr);
}
table.appendChild(tb);
}

Combine HTML Table Rows with Javascript

Is there an easy way to combine rows in an HTML table where the first column is the same? I basically have a table set up like:
<table>
<tr><td>test</td><td>12345</td><td>12345</td><tr>
<tr><td>test</td><td>12345</td><td>12345</td><tr>
<tr><td>test2</td><td>12345</td><td>12345</td><tr>
<tr><td>test</td><td>12345</td><td>12345</td><tr>
<tr><td>test2</td><td>12345</td><td>12345</td><tr>
</table>
and I want it to generate:
<table>
<tr><td>test</td><td>37035</td><td>37035</td><tr>
<tr><td>test2</td><td>24690</td><td>24690</td><tr>
</table>
using jQuery:
var map = {};
$('table tr').each(function(){
var $tr = $(this),
cells = $tr.find('td'),
mapTxt = cells.eq(0).text();
if(!map[mapTxt]){
map[mapTxt] = cells;
} else {
for(var i=1, l=cells.length; i<l; i++){
var cell = map[mapTxt].eq(i);
cell.text(parseInt(cell.text()) + parseInt(cells[i].text()));
}
$tr.remove();
}
});
this is a "dumb" script -- no error handling for cases like different number of cells, fields being non-numeric, etc. Add those if necessary.
Also, depending on how it's generated, it's better to do this server-side.
Here's a plain JavaScript version.
window.onload = function() {
var table = document.getElementById('mytable');
var tr = table.getElementsByTagName('tr');
var combined = Array();
for (i = 0; i < tr.length; i++) {
var td = tr[i].getElementsByTagName('td');
var key = td[0].innerText;
if (!combined[key]) {//if not initialised
combined[key] = Array();
for (j = 0; j < td.length - 1; j++) combined[key][j] = 0;
}
for (j = 0; j < td.length - 1; j++)
combined[key][j] += parseInt(td[j + 1].innerText);
}
while (table.hasChildNodes()) table.removeChild(table.lastChild);
var tbody = document.createElement('tbody');//needed for IE
table.appendChild(tbody);
for (var i in combined) {
tr = document.createElement('tr');
tbody.appendChild(tr);
td = document.createElement('td');
td.innerText = i;
tr.appendChild(td);
for (j = 0; j < combined[i].length; j++) {
td = document.createElement('td');
td.innerText = combined[i][j];
tr.appendChild(td);
}
}
}
This will work on tables with any number of rows and any number of cells. I suppose you want to make the sum for every column, that's what this script does.
And as cwolves mentioned, it is more logical to do this serverside. Users that have JS disabled will see the not so clean uncombined table.

Categories