Error "Cannot read property 'appendChild' of null at generateTable" - javascript

Can someone please shine some light on my this error is tossed? outputTable is properly referenced, and my JS file with the array countries is properly formatted.
I reckon I am appending erroneously, but I have tried all that I can.
PS if youre going to downvote, at least please tell me how to improve my questions in the future. I couldnt find a different question that exists already that matches my issue.
window.onload = generateTable();
function generateTable() {
// get the reference for the body
var outputTable = document.getElementById('outputTable');
// revoke existing Body element
if (outputTable) {
outputTable.removeChild(outputTable);
}
// creates a <tbody> element
var tableBody = document.createElement('tbody');
// creating all table rows
for (var i = 0; i < countries.length; i++) {
// creates a table row
var row = document.createElement('tr');
// create table column for flag
var colFlag = document.createElement('td');
//create image element in flag column
var flag = document.createElement('img');
flag.src = 'flags/' + countries[i].Code.toLowerCase() + '.png';
flag.alt = countries[i].Code;
row.appendChild(colFlag);
//append flag to flag column
colFlag.appendChild(flag);
// create table column for Code
var colCode = document.createElement('td');
//append code to code column
colCode.appendChild(document.createTextNode(countries[i].Code));
row.appendChild(colCode);
// create table column for country //**ENGLISH */
var colCountry = document.createElement('td');
colCountry.appendChild(document.createTextNode(countries[i].Name.English));
row.appendChild(colCountry);
// create table column for continent
var colCont = document.createElement('td');
colCont.appendChild(document.createTextNode(countries[i].Continent));
row.appendChild(colCont);
// create table column for area
var colArea = document.createElement('td');
colArea.appendChild(document.createTextNode(countries[i].AreaInKm2));
row.appendChild(colArea);
// create table column for population
var colPop = document.createElement('td');
colPop.appendChild(document.createTextNode(countries[i].Population));
row.appendChild(colPop);
// create table column for capital of country
var colCap = document.createElement('td');
colCap.appendChild(document.createTextNode(countries[i].Capital));
row.appendChild(colCap);
// attach columns to row
tableBody.appendChild(row);
outputTable.appendChild(tableBody);
}
// add the row to the end of the table body
document.body.appendChild(outputTable);
}

Related

how to replace old table rows with new rows using javascript

I have created a dynamic table in html click here to view image the rows are created dynamically in javascript please refer the image click here to view image the data for table is fetched from firebase.
The problem I am facing is that the rows are getting added at the end of the table repeatedly resulting in duplicate rows please refer the image click here to view image how do I remove old rows and add new updated rows using javascript.
I have updated the snapshot.forEach loop with comments.
snapshot.forEach(function (data) {
var val = data.val();
var trow = document.createElement('tr');
var tdata = document.createElement('td');
var tdata1 = document.createElement('td');
tdata.innerHTML = val.Name;
tdata1.innerHTML = val.Votes;
trow.appendChild(tdata);
trow.appendChild(tdata1);
// set the Name as data-id attribute
// which can be used to query the existing row
tdata.setAttribute('data-id', val.Name);
// append the trow to tbdy
// only if there's no row with data-id value of val.Name
// otherwise update the vote column of the existing row
var existingRow = tbdy.querySelector('[data-id="' + val.Name + '"]');
if (!existingRow) {
tbdy.appendChild(trow);
} else {
existingRow.querySelectorAll("td")[1].innerHTML = val.Votes;
}
});

Check table overlap with JavaScript & jQuery

I'm developing timetable web app and I have some problem with it. When I click the button clicked row data will go to under table which I set 'selected subject' table.
And I want to make it if the subject code are already in selected subject, alert the message and prevent put data in to second table.
At first time I thought When I click the add button, make a array and put the subject Code data, and every time when I click the add button, check the array if the subject code are already in there or not.
And Here's my code.
// Add Subject Button Click Event
$('.checkBtn').click(function () {
let checkBtn = $(this);
let tr = checkBtn.parent().parent();
let td = tr.children();
let table = document.getElementById('subjectSelectBody');
let row = table.insertRow();
let subjectCode = row.insertCell(0);
let subjectName = row.insertCell(1);
let credit = row.insertCell(2);
let major = row.insertCell(3);
let day = row.insertCell(4);
let time = row.insertCell(5);
let deleteButton = row.insertCell(6);
// Get Select Tag data
let subject = td.eq(0).text();
let x = document.getElementById(subject).value;
// put data into second table (selected table)
subjectCode.innerHTML = td.eq(0).text();
subjectName.innerHTML = td.eq(1).text();
credit.innerHTML = Number(td.eq(2).text());
major.innerHTML = td.eq(3).text();
day.innerHTML = x;
time.innerHTML = td.eq(5).text();
deleteButton.innerHTML = "<button>delete</button>";
// When clicks delete button, remove the data from second table
$('button').click(function () {
$(this).parents('tr').first().remove();
});
// Create subject add Array to check overlap
let sbjCodeArr=new Array();
sbjCodeArr.push(td.eq(0).text());
console.log(sbjCodeArr);
// Total Array to deliver to server
let tdArr = [td.eq(0).text(), td.eq(1).text(), Number(td.eq(2).text()), td.eq(3).text(), x, td.eq(5).text()];
console.log(tdArr);
})

Format data from database if data contains a tab-sign

I have a website in wich users input text into a textarea.
This text is saved into a database table and is later shown in a div element
Sometimes a user paste data from excel into the textarea, i wish to retain the table layout from excel after i pull it from the database and present it on my webpage
Example:
test cat1 cat2
data1 1 2
data2 3 5
data3 6 5
Is it possible (probably with js) that on loading the page a code checks if a tab-sign is in the data? And if yes.. format that data as a html table?
TRY As below. Just giving you idea.
var body = document.getElementsByTagName('body')[0];
var text = document.getElementByID("txtareaID").value;
var isTab = text.indexOf("\t");
if(isTab != '-1')
{
var tableCell = text.split("\t");
var table = document.createElement('table');
var tbdy = document.createElement('tbody');
var tr = document.createElement('tr');
for (var i = 0; i < tableCell.length ; i++) {
var td = document.createElement('td');
td.innerText = tableCell[i];
tr.appendChild(td);
}
tbdy.appendChild(tr);
}
tbl.appendChild(tbdy);
body.appendChild(tbl);
}
You can check for tab characters using \t to see if the character exists in the string. Something like this
var text = "test cat1 cat2 data1 1 2 data2 3 5 data3 6 5";
var tabsFound = text.indexOf("\t");

Reload HTML table after every AJAX call

My sequential AJAX calls keep appending rows to my HTML table, which I don't want. I want my table to be refreshed/reload on every call with new data, and not appended.
My Code:
var data = $('#data_input').val();
var tableRef = document.getElementById('data_table');
$.getJSON("/data/"+data, function(dataState)
{
// ...
for(var dataId in dataState)
{
var row = document.createElement("tr");
// creating new cells in a row with the data
tableRef.appendChild(row);
}
}
So I'm fetching the reference to my HTML table with var tableRef = document.getElementById('data_table');, in the for-loop, I'm creating rows and appending them to the HTML table with tableRef.appendChild(row);. The problem is that on any sequent $.getJSON call, the table gets further appended. How do I refresh my table on every call, ie. delete data from the previous call, and fill data from a new call?
You can delete the rows after getting the data from the server
$.getJSON("/data/"+data, function(dataState) {
$("#data_table tr").remove();
//...
for(var dataId in dataState) {
var row = document.createElement("tr");
// creating new cells in a row with the data
tableRef.appendChild(row);
}
}
});
Note that it will also remove the headers of the table, if you want to remove the data only and keep the headers, you only remove the rows inside tbody tag i.e $("#data_table tbody tr").remove();
You can use jQuery to delete every children of type tr with $("#data_table tr").remove();.
So you'll have something like this:
var data = $('#data_input').val();
var tableRef = document.getElementById('data_table');
$.getJSON("/data/"+data, function(dataState)
{
// ...
$("#data_table tr").remove();
for(var dataId in dataState)
{
var row = document.createElement("tr");
// creating new cells in a row with the data
tableRef.appendChild(row);
}
}

How do I loop through XML nodes in JavaScript?

I'm trying to loop through XML nodes containing information about users to create an HTML table on my website.
This is what the XML looks like:
<websites_name>
<user>...</user>
<user>...</user>
.
.
.
</websites_name>
And this is the code I'm trying to parse it with:
for(var user in xmlhttp.getElementsByTagName('user')){ //fix this row to me
//Create a new row for tbody
var tr = document.createElement('tr');
document.getElementById('tbody').appendChild(tr);
}
UPDATE
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","some URL",true);
xmlhttp.send();
var xmlDoc = xmlhttp.responseXML;
var root = xmlDoc.getElementsByTagName('websites_name');
for(var i=0, i<root[0].childNodes.length,i++){
//Create a new row for tbody
var tr = document.createElement('tr');
document.getElementById('tbody').appendChild(tr);
}
One of the least intuitive things about parsing XML in JavaScript is that the text inside the element tags is actually a node you have to traverse into.
Assuming it's <user>text data</user>, you not only have to traverse into the text node of the user element to extract your text data, but you have to create a text node with that data in the DOM to see it. See nodeValue and and createtextnode:
// get XML
var xml = xhr.responseXML;
// get users
var users = xml.getElementsByTagName("user");
for (var i = 0; i < users.length; i++) {
var user = users[i].firstChild.nodeValue;
var tr = document.createElement("tr");
var td = document.createElement("td");
var textNode = document.createTextNode(user);
td.appendChild(textNode);
tr.appendChild(td);
document.getElementById("tbody").appendChild(tr);
}

Categories