Why failed to generate dynamic table with Javascript? - javascript

I want to generate dynamic table with Javascript, want to generate table like this table:
<table>
<tbody>
<tr>
<th>Owner</th>
<th>Number</th>
</tr>
<tr>
<td>aaa</td>
<td> 3 </td>
</tr>
...
</tbody>
</table>
then I write a script to generate the table, but I can't get correct table, I don't know where has problem, could anyone help to check it?
var arrName = ['aaa', 'bbb','ccc'];
var arrNumber = [3, 2, 4];
if (arrName.length != 0 && arrNumber.length != 0)
{
var table = document.createElement('table');
var tbody = document.createElement('tbody');
var tr_header = document.createElement('tr');
var th_owner = document.createElement('th');
var th_number = document.createElement('th');
th_owner.appendChild(document.createTextNode('Owner'));
th_number.appendChild(document.createTextNode('Number'));
tr_header.appendChild(th_owner);
tr_header.appendChild(th_number);
tbody.appendChild(tr_header);
for (var i = 0; i < arrName.length; i++)
{
var tr_details = document.createElement('tr');
var td_owner = document.createElement('td');
var td_count = document.createElement('td');
td_owner.appendChild(document.createTextNode(arrName[i].toString()));
td_count.appendChild(document.createTextNode(arrNumber[i].toString()));
tr_details.appendChild(td_owner);
tr_details.appendChild(td_count);
tbody.appendChild(tr_details);
}
table.appendChild(tbody);
}
}

Your code is working perfectly. Maybe you just missed to add the table to the page.
I just added bellow code to the end:
var body = document.getElementsByTagName('body');
body[0].appendChild(table);
Check the test page I wrote:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<script>
document.addEventListener('DOMContentLoaded', () => {
var arrName = ['aaa', 'bbb','ccc'];
var arrNumber = [3, 2, 4];
if (arrName.length != 0 && arrNumber.length != 0)
{
var table = document.createElement('table');
var tbody = document.createElement('tbody');
var tr_header = document.createElement('tr');
var th_owner = document.createElement('th');
var th_number = document.createElement('th');
th_owner.appendChild(document.createTextNode('Owner'));
th_number.appendChild(document.createTextNode('Number'));
tr_header.appendChild(th_owner);
tr_header.appendChild(th_number);
tbody.appendChild(tr_header);
for (var i = 0; i < arrName.length; i++)
{
var tr_details = document.createElement('tr');
var td_owner = document.createElement('td');
var td_count = document.createElement('td');
td_owner.appendChild(document.createTextNode(arrName[i].toString()));
td_count.appendChild(document.createTextNode(arrNumber[i].toString()));
tr_details.appendChild(td_owner);
tr_details.appendChild(td_count);
tbody.appendChild(tr_details);
}
table.appendChild(tbody);
var body = document.getElementsByTagName('body');
body[0].appendChild(table);
}
});
</script>
</body>
</html>

Related

Dynamically created html table data not showing in order as expected

function CreateWeakHeader(name) {
var tr = document.createElement('tr');
var td = document.createElement('td');
td.classList.add("cal-usersheader");
td.style.color = "#000";
td.style.backgroundColor = "#7FFF00";
td.style.padding = "0px";
td.appendChild(document.createTextNode(name));
tr.appendChild(td);
var thh = document.createElement('td');
thh.colSpan = "31";
thh.style.color = "#FFFFFF";
thh.style.backgroundColor = "#7FFF00";
tr.appendChild(thh);
return tr;
}
function htmlTable(data, columns) {
var header = document.createElement("div");
header.classList.add("table-responsive");
var header2 = document.createElement("div");
header2.id = "calplaceholder";
header.appendChild(header2);
var header3 = document.createElement("div");
header3.classList.add("cal-sectionDiv");
header2.appendChild(header3);
if ((!columns) || columns.length == 0) {
columns = Object.keys(data[0]);
}
var tbe = document.createElement('table');
tbe.classList.add("table", "table-striped", "table-bordered");
var thead = document.createElement('thead');
thead.classList.add("cal-thead");
tbe.appendChild(thead);
var tre = document.createElement('tr');
for (var i = 0; i < columns.length; i++) {
var the = document.createElement('th');
the.classList.add("cal-toprow");
the.textContent = columns[i];
tre.appendChild(the);
}
thead.appendChild(tre);
var tbody = document.createElement('tbody');
tbody.classList.add("cal-tbody");
tbe.appendChild(tbody);
var week = 0;
//tbody.appendChild(CreateWeakHeader("Week " + week));
var tre = document.createElement('tr');
for (var j = 0; j < data.length; j++) {
if (j % 7 == 0) {
week++;
tbody.appendChild(CreateWeakHeader("Week " + week));
}
var thead = document.createElement('td');
thead.classList.add("ui-droppable");
thead.appendChild(data[j]);
tre.appendChild(thead);
tbody.appendChild(tre);
}
header3.appendChild(tbe);
document.body.appendChild(header);
}
$("#tb").click(function() {
var header = document.createElement("div");
header.innerHTML = "test";
var d = [header, header, header, header, header, header, header, header];
htmlTable(d, days);
});
var days = ['Maandag', 'Dinsdag', 'Woensdag', 'Donderdag', 'Vrijdag', 'Zaterdag', 'Zondag'];
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.0/dist/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.0/dist/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" id="tb">CreateTable</button>
I'm trying to order the data that I get from my server to match the columns of my table.
My table columns are days from Monday to Sunday. When my data has more than 7items it needs to separate with another td. The td shows me week 1 and when my data has more than 7 items it needs to separate again that shows week 2 etc.
Update
Im now using a snipped verdion of my code.
Hope someone can help me out with this.
Thank you
There's a few things going on in the code that are problematic.
An attempt to add the table cells to the row, and the row to the table, was made on each iteration of the for loop. That would have produced a lot of rows with single cells had it worked.
It didn't work because there was only ever a single instance of tre, the row variable. So that meant the line tbody.appendChild(tre); did nothing, since appendChild won't append an element that already has a parent element.
Because your data was an array of references to HTMLElements with parents, appending them using appendChild did nothing for the same reason.
I've amended the code below to take care of all of these situations.
Firstly, the code will append a clone of the data to the cell if it's an HTMLElement. I expect in your real code you won't need this, but for this example, why not? It then appends the cell to the row and continues to the next data element.
Secondly, when the data iterator is at 7, before it appends the "Week N" header, it appends a clone of the row, if it has cells on it.
Finally, after appending the clone of the row, the code will reset the row variable to a new instance of a tr element, with no cells.
I also made some variable name and formatting changes to your code just so I could more easily work with it.
function CreateWeakHeader(name) {
var tr = document.createElement('tr');
var td = document.createElement('td');
td.classList.add("cal-usersheader");
td.style.color = "#000";
td.style.backgroundColor = "#7FFF00";
td.style.padding = "0px";
td.appendChild(document.createTextNode(name));
tr.appendChild(td);
var thh = document.createElement('td');
thh.colSpan = "6"; // "31"; Why 31? A week has 7 days...
thh.style.color = "#FFFFFF";
thh.style.backgroundColor = "#7FFF00";
tr.appendChild(thh);
return tr;
}
function htmlTable(data, columns) {
var header = document.createElement("div");
header.classList.add("table-responsive");
var header2 = document.createElement("div");
header2.id = "calplaceholder";
header.appendChild(header2);
var header3 = document.createElement("div");
header3.classList.add("cal-sectionDiv");
header2.appendChild(header3);
if ((!columns) || columns.length == 0) {
columns = Object.keys(data[0]);
}
var tbe = document.createElement('table');
tbe.classList.add("table", "table-striped", "table-bordered");
var thead = document.createElement('thead');
thead.classList.add("cal-thead");
tbe.appendChild(thead);
var tre = document.createElement('tr');
for (var i = 0; i < columns.length; i++) {
var the = document.createElement('th');
the.classList.add("cal-toprow");
the.textContent = columns[i];
tre.appendChild(the);
}
thead.appendChild(tre);
var tbody = document.createElement('tbody');
tbody.classList.add("cal-tbody");
tbe.appendChild(tbody);
var week = 0;
//tbody.appendChild(CreateWeakHeader("Week " + week));
var tre = document.createElement('tr');
for (var j = 0; j < data.length; j++) {
if (j % 7 == 0) {
week++;
/* Major changes start here */
// if the row has cells
if (tre.querySelectorAll('td').length) {
// clone and append to tbody
tbody.appendChild(tre.cloneNode(true));
// reset table row variable
tre = document.createElement('tr');
}
// then append the Week header
tbody.appendChild(CreateWeakHeader("Week " + week));
}
var td = document.createElement('td');
td.classList.add("ui-droppable");
// Set the value of the cell to a clone of the data, if it's an HTMLElement
// Otherwise, make it a text node.
var value = data[j] instanceof HTMLElement ?
data[j].cloneNode(true) :
document.createTextNode(data[j]);
td.appendChild(value);
tre.appendChild(td);
}
// If the number of data elements is not evenly divisible by 7,
// the remainder will be on the row variable, but not appended
// to the tbody, so do that.
if (tre.querySelectorAll('td').length) {
tbody.appendChild(tre.cloneNode(true));
}
header3.appendChild(tbe);
document.body.appendChild(header);
}
$("#tb").click(function() {
var header = document.createElement("div");
header.innerHTML = "test";
var d = [header, header, header, header, header, header, header, header];
htmlTable(d, days);
});
var days = ['Maandag', 'Dinsdag', 'Woensdag', 'Donderdag', 'Vrijdag', 'Zaterdag', 'Zondag'];
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.0/dist/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.0/dist/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" id="tb">CreateTable</button>

how to loop an array and get only the value of a particular index

I am building a dynamic table where i want only 3 values from my json to display and make one a link which when clicked on, the rest displays. Below is my code kindly assist please.
var myInvestment =[
{
"investmentNo":"00032",
"amount":"70000",
"status": "Expired",
"repayAmt":"70500",
"description": "Official",
"maturityDate":"2020-10-31"
},
{
"investmentNo":"00034",
"amount":"5000",
"status": "Current",
"repayAmt":"6000",
"description": "School fees",
"maturityDate":"2022-03-31"
}
]
var investmentTable = document.querySelector("#investmentTable");
if(myInvestment.length>0){
var col = []; // define an empty array
for (var i = 0; i < myInvestment.length; i++) {
for (var key in myInvestment[i]) {
if (col.indexOf(key) === -1) {
col.push(key);
}
}
}
// CREATE TABLE HEAD .
var tHead = document.createElement("tHead");
// CREATE ROW FOR TABLE HEAD .
var hRow = document.createElement("tr");
// ADD COLUMN HEADER TO ROW OF TABLE HEAD.
tHead.appendChild(hRow);
investmentTable.appendChild(tHead);
// CREATE TABLE BODY .
var tBody = document.createElement("tbody");
// ADD COLUMN HEADER TO ROW OF TABLE HEAD.
for (var i = 0; i < myInvestment.length; i++) {
var bRow = document.createElement("tr");
// CREATE ROW FOR EACH RECORD .
var td = document.createElement("td");
td.innerHTML = i+1;
bRow.appendChild(td);
for (var j = 0; j < 3; j++) {
var td = document.createElement("td");
if (j==0) {
td.innerHTML = ''+myInvestment[i][col[j]]+ '';
bRow.appendChild(td);
}else{
td.innerHTML = myInvestment[i][col[j]];
bRow.appendChild(td);
}if (j==2) {
td.innerHTML = '<div class="badge">'+myInvestment[i][col[j]]+ '</div>';
if (td.textContent=="Current") {
td.innerHTML = '<div class="badge badge-success">'+myInvestment[i][col[j]]+ '</div>';
} else {
td.innerHTML = '<div class="badge badge-danger">'+myInvestment[i][col[j]]+ '</div>';
}
}
tBody.appendChild(bRow)
}
investmentTable.appendChild(tBody);
}
}
This is my modal function that will display the second table
function invModalView(k,myInvestment){
var modal = document.getElementById("modal-block-normal");
modal.style.display = "block";
var investNo = document.getElementById("investNo");
var investmentTableModal = document.querySelector("#investmentTableModal");
myInvestment
.forEach((item, i) => {
var row = investmentTable.insertRow();
row.insertCell(0).innerHTML = item.repayAmt;
row.insertCell(1).innerHTML = item.description;
row.insertCell(2).innerHTML = item.maturityDate;
});
}
}
HTML
<table class="table table-bordered table-striped table-vcenter table-responsive" id="investmentTableModal">
<thead id="invtableHead">
<tr >
<th class="d-sm-table-cell" style="width: 30%;">Repayment Amount</th>
<td id="repayAmt"></td>
</tr>
<tr>
<th class="d-sm-table-cell" style="width: 30%;">Description</th>
<td id="description"></td>
</tr>
<tr>
<th class="d-sm-table-cell" style="width: 30%;">Maturity Date</th>
<td id = "matureDate"></td>
</tr>
</table>
i want when a user clicks on myInvestment.investmentNo[0], only the repaymentamt, description and maturityDate of myInvestment[0] will show
That's a lot of spaghetti code to go through, so I'm not even going to try.
In jQuery, what people normally do is they iterate over the array and construct each button, and then place each button on the dom. Then, they apply a $.click() on that button, and inside the .click callback they can create a clojure over the original item they created a button for.
like this: https://jsfiddle.net/0d8aL9xr/
var items = [{title: 'a bouncing ball', id: 1}, {title: 'a rubber duck', id: 2}];
items.forEach(item => {
const $newButton = $(`<button>${item.title}</button>`);
$('.buttons').append($newButton);
$newButton.click(function() {
$('#item-id').val(item.id);
$('#item-name').val(item.title);
})
})
function setSession(key,value){
window.localStorage.setItem(key, value);
}
function getSession(key){
return window.localStorage.getItem(key)
;
}
function unsetSession(key){
window.localStorage.removeItem(key)
;
}
////// Investment page scripts //////
function investmentData(){
var InvData = getSession("InvData");
var myInvestment = JSON.parse(InvData);
var investmentTable = document.querySelector("#investmentTable");
if(myInvestment.investments.length>0){
var col = []; // define an empty array
for (var i = 0; i < myInvestment.investments.length; i++) {
for (var key in myInvestment.investments[i]) {
if (col.indexOf(key) === -1) {
col.push(key);
}
}
}
// CREATE TABLE HEAD .
var tHead = document.querySelector("#tableHead");
// CREATE ROW FOR TABLE HEAD .
var hRow = document.querySelector("#tableRow");
// ADD COLUMN HEADER TO ROW OF TABLE HEAD.
tHead.appendChild(hRow);
investmentTable.appendChild(tHead);
// CREATE TABLE BODY .
var tBody = document.createElement("tbody");
// ADD COLUMN HEADER TO ROW OF TABLE HEAD.
for (var i = 0; i < myInvestment.investments.length; i++) {
var bRow = document.createElement("tr");
// CREATE ROW FOR EACH RECORD .
var td = document.createElement("td");
td.innerHTML = i+1;
bRow.appendChild(td);
for (var j = 0; j < 3; j++) {
var td = document.createElement("td");
if (j==0) {
td.innerHTML = ''+myInvestment.investments[i][col[j]]+ '';
bRow.appendChild(td);
}else{
td.innerHTML = myInvestment.investments[i][col[j]];
bRow.appendChild(td);
}if (j==2) {
td.innerHTML = '<div class="badge">'+myInvestment.investments[i][col[j]]+ '</div>';
if (td.textContent=="Current") {
td.innerHTML = '<div class="badge badge-success">'+myInvestment.investments[i][col[j]]+ '</div>';
} else {
td.innerHTML = '<div class="badge badge-danger">'+myInvestment.investments[i][col[j]]+ '</div>';
}
}
tBody.appendChild(bRow)
}
investmentTable.appendChild(tBody);
}
}
}
function invModalView(k){
$('#investmentTableModal').empty();
var myInv = JSON.parse(getSession("InvData"));
var modal = document.getElementById("modal-block-normal");
modal.style.display = "block";
var investmentTableModal = document.querySelector("#investmentTableModal");
// CREATE TABLE BODY .
var tBody = document.createElement("tbody");
// // ADD COLUMN HEADER TO ROW OF TABLE HEAD.
// // Investment No
var bRow = document.createElement("tr");
var th = document.createElement("th");
th.innerHTML = "Investment No";
var td2 = document.createElement("td");
td2.style.width = "30%";
th.style.width = "30%";
td2.innerHTML = myInv.investments[k].investmentNo;
bRow.appendChild(th);
bRow.appendChild(td2);
tBody.appendChild(bRow);
investmentTableModal.appendChild(tBody)
// Investment duration
var tBody = document.createElement("tbody");
var bRow = document.createElement("tr");
var th = document.createElement("th");
th.innerHTML = "Duration";
var td2 = document.createElement("td");
td2.innerHTML = myInv.investments[k].duration;
bRow.appendChild(th);
bRow.appendChild(td2);
tBody.appendChild(bRow)
investmentTableModal.appendChild(tBody);
// investment start date
var tBody = document.createElement("tbody");
var bRow = document.createElement("tr");
var th = document.createElement("th");
th.innerHTML = "startDate";
var td2 = document.createElement("td");
td2.innerHTML = myInv.investments[k].startDate;
bRow.appendChild(th);
bRow.appendChild(td2);
tBody.appendChild(bRow)
investmentTableModal.appendChild(tBody);
// investment yield
var tBody = document.createElement("tbody");
var bRow = document.createElement("tr");
var th = document.createElement("th");
th.innerHTML = "Yield";
var td2 = document.createElement("td");
td2.innerHTML = myInv.investments[k].yield;
bRow.appendChild(th);
bRow.appendChild(td2);
tBody.appendChild(bRow)
investmentTableModal.appendChild(tBody);
// investment repayment Amount
var tBody = document.createElement("tbody");
var bRow = document.createElement("tr");
var th = document.createElement("th");
th.innerHTML = "Repayment Amount";
var td2 = document.createElement("td");
td2.innerHTML = myInv.investments[k].repayAmt;
bRow.appendChild(th);
bRow.appendChild(td2);
tBody.appendChild(bRow)
investmentTableModal.appendChild(tBody);
// investment description
var tBody = document.createElement("tbody");
var bRow = document.createElement("tr");
var th = document.createElement("th");
th.innerHTML = "Description";
var td2 = document.createElement("td");
td2.innerHTML = myInv.investments[k].description;
bRow.appendChild(th);
bRow.appendChild(td2);
tBody.appendChild(bRow)
investmentTableModal.appendChild(tBody);
// investment maturityDate
var tBody = document.createElement("tbody");
var bRow = document.createElement("tr");
var th = document.createElement("th");
th.innerHTML = "MaturityDate";
var td2 = document.createElement("td");
td2.innerHTML = myInv.investments[k].maturityDate;
bRow.appendChild(th);
bRow.appendChild(td2);
tBody.appendChild(bRow)
investmentTableModal.appendChild(tBody);
}
////// Create Localstorage for MyInvestment ////
var myInvestment = '{"investments":[{"investmentNo":"00032","amount":"70000","status": "Expired","duration": "2","startDate": "2020-02-02","yield": "2.60","repayAmt":"70500","description": "Official","maturityDate":"2020-10-31"},{"investmentNo":"00033","amount":"40000","status": "Current","duration": "3","startDate": "2019-01-05","yield": "12.0","repayAmt":"42000","description": "Personal","maturityDate":"2020-12-31"},{"investmentNo":"00034","amount":"5000","status": "Current","duration": "4","startDate": "5-04-2008","yield": "20.0","repayAmt":"6000","description": "School fees","maturityDate":"2022-03-31"}]}'
setSession("InvData",myInvestment);
I later succeeded in getting this. i think it would be nice to share for someone out there who might need it.

Javascript for add cells in table

I have a problem. I need insert cell in a row. The content of cell is an element of an array. But is duplicate... Here my code:
function addFila() {
var iframe = document.getElementById('myFrame');
var table = iframe.contentDocument.getElementsByClassName("head_to_head h2h_home")[0];
var row = table.insertRow(1);
var fila = ["fecha", "liga", "equipolocal", "equipovisitante", "goleslocal", "golesvisitante"];
for (let i = 0; i < 6; i++) {
row.insertCell(i);
for (let x = 0; x <= fila.length; x++) {
row.insertCell(i).innerHTML = fila[i];
}
}
}
What is wrong?
row.insertCell() return new cell. If you want to create cell and use it you should save created cell in variable. You get duplicate because you call insertCell twice. I hope code below can help you
var table = document.querySelector(".table");
var row = table.insertRow(-1);
var fila = ["fecha", "liga", "equipolocal", "equipovisitante", "goleslocal", "golesvisitante"];
for (let i = 0; i < fila.length; i++) {
const insertedCell = row.insertCell(i);
insertedCell.textContent = fila[i];
}
table td {
border: 1px solid lime;
}
<table class="table">
<tbody>
<tr>
<td>cell_1_1</td>
<td>cell_1_2</td>
</tr>
<tr>
<td>cell_2_1</td>
<td>cell_2_2</td>
</tr>
</tbody>
</table>

Datatable not working properly

So I am generating a table with results which are returned from a JSON that is searched through and I would like to table to have pagionation, search, sorting options so I decided to use Data Tables. The table is being generated and populated with the correct results but the sorting options, the search and the pagination options do not appear at all. What am I doing wrong?
<!DOCTYPE html>
<html lang="en">
<head>
<title>Конкуренција</title>
</head>
<body>
<div id="cars" class="cars-container"></div>
<label for="amount">Цена:</label>
<input type="text" class="price-range-slider" id="amount" onclick="myFunction()" readonly style="border:0; color:#f6932f; font-weight:bold">
<div id="slider-range" style="width:300px"></div>
<br>
<p>
<label for="sili">Коњски сили:</label>
<input type="text" id="sili" onclick="myFunction()" readonly style="border:0; color:#f6931f; font-weight:bold;">
<div id="rejndz" style="width:300px" ></div>
<div>
<h4><label>Бренд</label></h4>
<select id="brand" multiple="multiple" onclick="myFunction()" data- style="btn-primary">
</select>
</div>
<br>
<div>
<h4><label>Тип на мотор</label></h4>
<select id="engineCap" multiple="multiple" onclick="myFunction()" >
</select>
<button onclick="myFunction(); dataTable(); ">Барај</button>
</table>
var selected = [];
var kapacitet = [];
var cena = [];
var hp = [];
var niza = [];
var finalKola = [];
function addTable() {
document.getElementById("results").innerHTML = "";
var myTableDiv = document.getElementById("results")
var tableBody = document.createElement('TBODY')
myTableDiv.border = '1'
myTableDiv.appendChild(tableBody);
var heading = [];
heading[0] = "Бренд"
heading[1] = "Модел"
heading[2] = "Капацитет"
heading[3] = "Коњски сили"
heading[4] = "Цена"
//koloni
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (a = 0; a < heading.length; a++) {
var th = document.createElement('TH')
th.width = '75';
th.appendChild(document.createTextNode(heading[a]));
tr.appendChild(th);
}
//table rows
for (a = 0; a < finalKola.length; a++) {
var tr = document.createElement('TR');
var td = document.createElement('TD')
td.appendChild(document.createTextNode(finalKola[a].Brand));
tr.appendChild(td);
var td = document.createElement('TD')
td.appendChild(document.createTextNode(finalKola[a].Model));
tr.appendChild(td);
var td = document.createElement('TD')
td.appendChild(document.createTextNode(finalKola[a].engineCap));
tr.appendChild(td);
var td = document.createElement('TD')
td.appendChild(document.createTextNode(finalKola[a].sili));
tr.appendChild(td);
var td = document.createElement('TD')
td.appendChild(document.createTextNode(finalKola[a].amount + " €"));
tr.appendChild(td);
tableBody.appendChild(tr);
}
$(document).ready(function (){
{
$('#results').dataTable();
}
});
}
These are the errors I get in console:
Uncaught TypeError: Cannot read property 'mData' of undefined
at HTMLTableCellElement.<anonymous> (jquery.dataTables.min.js:88)
at Function.each (jquery.js:368)
at HTMLTableElement.<anonymous> (jquery.dataTables.min.js:88)
at Function.each (jquery.js:368)
at jQuery.fn.init.each (jquery.js:157)
at jQuery.fn.init.p [as dataTable] (jquery.dataTables.min.js:80)
at dataTable (index.html:268)
at HTMLButtonElement.onclick (index.html:75)
Assigning value to finalKola in the following code. This code takes values from two range slider and two buttons and searches through a JSON.
for(var u=0;u<koli.length;u++)
{
if((koli[u].sili > minSili) && (koli[u].sili < maxSili) && (parseInt(koli[u].amount.replace(',','')) > minCena) && (parseInt(koli[u].amount.replace(',','')) < maxCena))
{
if( (kapacitet.length > 0 && $.inArray(koli[u].engineCap,kapacitet) != -1) &&
(selected.length > 0 && $.inArray(koli[u].Brand,selected) != -1))
{
finalKola.push(koli[u]);
}
else if(kapacitet.length == 0 && selected.length == 0)
{
finalKola.push(koli[u]);
}
else if((kapacitet.length > 0 && $.inArray(koli[u].engineCap,kapacitet) != -1) &&
(selected.length == 0))
{
finalKola.push(koli[u]);
}
else if((selected.length > 0 && $.inArray(koli[u].Brand,selected) != -1) &&
(kapacitet.length == 0))
{
finalKola.push(koli[u]);
}
}
}
I think DataTable is not applying on your table as you are applying datatable on $(document).ready and creating table in your function.
You can apply datatable after you have created the table.
function addTable() {
document.getElementById("results").innerHTML = "";
var myTableDiv = document.getElementById("results")
var tableBody = document.createElement('TBODY')
myTableDiv.border = '1'
myTableDiv.appendChild(tableBody);
var heading = [];
heading[0] = "Бренд"
heading[1] = "Модел"
heading[2] = "Капацитет"
heading[3] = "Коњски сили"
heading[4] = "Цена"
//koloni
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (a = 0; a < heading.length; a++) {
var th = document.createElement('TH')
th.width = '75';
th.appendChild(document.createTextNode(heading[a]));
tr.appendChild(th);
}
//table rows
for (a = 0; a < finalKola.length; a++) {
var tr = document.createElement('TR');
var td = document.createElement('TD')
td.appendChild(document.createTextNode(finalKola[a].Brand));
tr.appendChild(td);
var td = document.createElement('TD')
td.appendChild(document.createTextNode(finalKola[a].Model));
tr.appendChild(td);
var td = document.createElement('TD')
td.appendChild(document.createTextNode(finalKola[a].engineCap));
tr.appendChild(td);
var td = document.createElement('TD')
td.appendChild(document.createTextNode(finalKola[a].sili));
tr.appendChild(td);
var td = document.createElement('TD')
td.appendChild(document.createTextNode(finalKola[a].amount + " €"));
tr.appendChild(td);
tableBody.appendChild(tr);
}
$('#results').dataTable().fnDestroy();
$('#results').dataTable();
}
Your script is adding tbody before the thead, changed that to append Thead tr first and then tbody.
var selected = [];
var kapacitet = [];
var cena = [];
var hp = [];
var niza = [];
var finalKola = [];
function addTable() {
document.getElementById("results").innerHTML = "";
var myTableDiv = document.getElementById("results")
var tableBody = document.createElement('TBODY')
myTableDiv.border = '1'
var heading = [];
heading[0] = "Бренд"
heading[1] = "Модел"
heading[2] = "Капацитет"
heading[3] = "Коњски сили"
heading[4] = "Цена"
//koloni
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (a = 0; a < heading.length; a++) {
var th = document.createElement('TH')
th.width = '75';
th.appendChild(document.createTextNode(heading[a]));
tr.appendChild(th);
}
myTableDiv.appendChild(tableBody);
//table rows
for (a = 0; a < finalKola.length; a++) {
var tr = document.createElement('TR');
var td = document.createElement('TD')
td.appendChild(document.createTextNode(finalKola[a].Brand));
tr.appendChild(td);
var td = document.createElement('TD')
td.appendChild(document.createTextNode(finalKola[a].Model));
tr.appendChild(td);
var td = document.createElement('TD')
td.appendChild(document.createTextNode(finalKola[a].engineCap));
tr.appendChild(td);
var td = document.createElement('TD')
td.appendChild(document.createTextNode(finalKola[a].sili));
tr.appendChild(td);
var td = document.createElement('TD')
td.appendChild(document.createTextNode(finalKola[a].amount + " €"));
tr.appendChild(td);
tableBody.appendChild(tr);
}
$(document).ready(function (){
{
$('#results').dataTable();
}
});
}

Dynamically remove elements with javascript

I got a javascript with a function that creates a table. Now I want the table to be updated/replaced each time I press the button again. I have tried some solutions I have found on the web but none seem to do what I want.
javascript
//Updates table
function myFunction(jsonObject) {
//Build array from the jsonObject
var customers = new Array();
var jsonArr = jsonObject['log'];
for(var i in jsonArr){
customers.push((jsonArr[i]['date']) );
customers.push((jsonArr[i]['time']) );
customers.push((jsonArr[i]['temp']) );
customers.push((jsonArr[i]['humidity']) );
}
//Remove existing tables.-----------------------THIS HAS NO EFFECT!
var myNode = document.getElementById('logDiv');
while (myNode.hasChildNodes()) {
alert("logDiv has nodes, removing them now!")
myNode.removeChild(myNode.firstChild);
}
//----------------------------------------------THIS HAS NO EFFECT!
var container = document.getElementById('logDiv');
var table = document.createElement('table');
var tbody = document.createElement('tbody');
table.className = "sortable";
//Adds table headers
var headers = ["Date", "Time", "Temp", "Hum"]
var row1 = document.createElement('tr');
for (var b = 0; b < 4; b++) {
var cell = document.createElement('th');
cell.textContent = headers[b];
row1.appendChild(cell);
counter++;
}
tbody.appendChild(row1);
var counter = 0;
// loop and create rows
for (i = 0; i < customers.length/4; i++) {
var values = customers[i];
var row = document.createElement('tr');
// loop and create columns
for (var b = 0; b < 4; b++) {
var cell = document.createElement('td');
cell.textContent = customers[counter];
row.appendChild(cell);
counter++;
}
tbody.appendChild(row);
}
table.appendChild(tbody);
container.appendChild(table);
}
html/php
<?php
$logLines = file('../../../home/shares/flower_hum/humid.log');
$entries = array_map("clean",$logLines);
$finalOutput = ['log' => $entries];
function clean($string){
return json_decode(rtrim(trim($string),','),true);
}
$json = json_encode($finalOutput);
?>
<html>
<head>
<script src="script.js" type="text/javascript"></script>
<script src="sorttable.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="style.css">
<meta charset="UTF-8">
<title>Antgus</title>
</head>
<body>
<button id="btnGenerate" type="button" onclick='myFunction(<?php echo $json ?>)'>Generate log</button>
<br><br>
<div id="logDiv"></div>
</body>
</html>

Categories