Datatable not working properly - javascript

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();
}
});
}

Related

Import values from rows of one table to header of another table

I want to import values from a row of one table to the header of another table. The issue is that my code copies the selected row to a div where table 2 is present.
Also, the row has an input field in which I can enter a value. It copies the input field as a whole and not just the value. How can I import only the value of the input field?
var table;
$('#createPlist').click(function plrList() {
count = Number($('#noofTiks').val());
caption = $('<caption>');
table = $('<table>');
table = $(table).css({
"border": "1px solid black"
});
var thead = $('<thead>');
var htr = $('<tr>');
var tbody = $('<tbody>');
for (var a = 0; a < count; a++) {
var row = $('<tr>');
for (var b = 0; b < 2; b++) {
var td = $("<td>");
td = $(td).css({
"border": "1px solid black"
});
if (b == 0) {
var srNo = a + 1;
td.append(srNo);
} else {
var input = $('<input>');
td.append(input);
}
row.append(td);
}
tbody.append(row);
}
var th = $('<th>');
th.append("Sr. No.");
htr.append(th);
th = $('<th>');
th.append("Player Name");
htr.append(th);
thead.append(htr);
table.append(thead);
table.append(tbody);
caption.append("Player List");
$('#pList').append(caption);
$('#pList').append(table);
});
$('#createPlist').on('click', function() {
$(this).prop('disabled', true);
});
$('#giveTik').click(function() {
count = Number($('#noofTiks').val());
for (h = 0; h < count; h++) {
var table = $('<table>');
table = $(table).css({
"border": "1px solid black",
"margin": "20px auto",
"width": "500px",
"height": "250px"
})
var thead = $('<thead>');
var tbody = $('<tbody>');
for (var i = 0; i < 3; i++) {
// append new row to body
var row = $('<tr>');
//var row = '';
for (var j = 0; j < 9; j++) {
// append new td to row
var td = $("<td>");
td = $(td).css({
"border": "1px solid black",
})
td.append("");
row.append(td);
}
tbody.append(row);
}
var showTable = $('#pList').find('tr').eq(h + 1); //NEED HELP HERE
console.log(showTable)
// For "selected" row of table1 ..
var rowFromTable1 = showTable;
// .. Take a clone/copy of it ..
var clonedRowFromTable1 = rowFromTable1.clone(); //NEED HELP HERE
// .. And append the cloned row to the thead of table2
$('#div').append(clonedRowFromTable1);
// thead.append(h + 1);
// table.append(thead);
table.append(tbody);
$('#div').append(table);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="noofTiks">
<div id="pList"></div>
<button class="btn btn-error" id="createPlist">OK</button>
<div id="div"></div>
<button id="giveTik">CREATE TICKETS</button>
Your current code was appending row to div because you where directly appending the clone row to #div instead you should append the cloned row to thead and then append this thead to table.Also i have replace cloned row td with th and added colspan .
Demo Code :
var table;
$('#createPlist').click(function plrList() {
count = Number($('#noofTiks').val());
caption = $('<caption>');
table = $('<table>');
table = $(table).css({
"border": "1px solid black"
});
var thead = $('<thead>');
var htr = $('<tr>');
var tbody = $('<tbody>');
for (var a = 0; a < count; a++) {
var row = $('<tr>');
for (var b = 0; b < 2; b++) {
var td = $("<td>");
td = $(td).css({
"border": "1px solid black"
});
if (b == 0) {
var srNo = a + 1;
td.append(srNo);
} else {
var input = $('<input>');
td.append(input);
}
row.append(td);
}
tbody.append(row);
}
var th = $('<th>');
th.append("Sr. No.");
htr.append(th);
th = $('<th>');
th.append("Player Name");
htr.append(th);
thead.append(htr);
table.append(thead);
table.append(tbody);
caption.append("Player List");
$('#pList').append(caption);
$('#pList').append(table);
});
$('#createPlist').on('click', function() {
$(this).prop('disabled', true);
});
$('#giveTik').click(function() {
count = Number($('#noofTiks').val());
for (h = 0; h < count; h++) {
var table = $('<table>');
table = $(table).css({
"border": "1px solid black",
"margin": "20px auto",
"width": "500px",
"height": "250px"
})
var thead = $('<thead>');
var tbody = $('<tbody>');
for (var i = 0; i < 3; i++) {
// append new row to body
var row = $('<tr>');
//var row = '';
for (var j = 0; j < 9; j++) {
// append new td to row
var td = $("<td>");
td = $(td).css({
"border": "1px solid black",
})
td.append("");
row.append(td);
}
tbody.append(row);
}
var showTable = $('#pList').find('tr').eq(h + 1); //NEED HELP HERE
// For "selected" row of table1 ..
var rowFromTable1 = showTable;
// .. Take a clone/copy of it ..
var clonedRowFromTable1 = rowFromTable1.clone();
//finding input value
var input_value = clonedRowFromTable1.find("input").val();
//getting sr.no
var texts = clonedRowFromTable1.find("td:first").text();
//replace td with th and add sr.no and input value
clonedRowFromTable1.find("td:first").replaceWith("<th colspan='9'>" + texts + " " + input_value + "</th>")
clonedRowFromTable1.find("td:last").remove()//remove next td
//append cloned elemnt to thead
thead.append(clonedRowFromTable1);
table.append(thead)//append to table
table.append(tbody);
$('#div').append(table);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="noofTiks">
<div id="pList"></div>
<button class="btn btn-error" id="createPlist">OK</button>
<div id="div"></div>
<button id="giveTik">CREATE TICKETS</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.

How to remove an entire table using javascript?

I have a calendar table, that shows the entire month's date, if user chose to see next month or previous I need to delete the entire table and replace the new table in that same place, at the moment each table is loading underneath the other because I cant get this to work.
I need to remove table from calendar-dates. but I had no luck. I have used removechild("tb") but didnt work, I also tried var test = document.getElementById("calendarDates");
test.removeChild(test.childNodes[0]);
Here is the code for the table:
document.getElementById("calendar-dates").appendChild(calendar);
Table:
//add calendar table
function get_calendar(day_no, days, m , y){
var table = document.createElement('table');
table.id = "tb";
var tr = document.createElement('tr');
//row for the day letters
for(var c=0; c<=6; c++){
var td = document.createElement('td');
td.innerHTML = "SMTWTFS"[c];
tr.appendChild(td);
}
table.appendChild(tr);
//create 2nd row
tr = document.createElement('tr');
var c;
for(c=0; c<=6; c++){
if(c == day_no){
break;
}
var td = document.createElement('td');
td.innerHTML = "";
tr.appendChild(td);
}
var count = 1;
for(; c<=6; c++){
var td = document.createElement('td');
td.innerHTML = count;
td.style.cursor = "pointer";
td.id = count;
td.onclick = function () {
m = m + 1;
document.getElementById("cDD").value = this.id + "/" + m + "/" + y;
document.getElementById("calendar-container").style.display = "none";
};
count++;
tr.appendChild(td);
}
table.appendChild(tr);
//rest of the date rows
for(var r=3; r<=7; r++){
tr = document.createElement('tr');
for(var c=0; c<=6; c++){
if(count > days){
table.appendChild(tr);
return table;
}
var td = document.createElement('td');
td.innerHTML = count;
td.style.cursor = "pointer";
td.id = count;
td.onclick = function () {
m = m + 1;
document.getElementById("cDD").value = this.id + "/" + m + "/" + y;
document.getElementById("calendar-container").style.display = "none";
};
count++;
tr.appendChild(td);
}
table.appendChild(tr);
}
return table;
}
The removeChild method takes a node, not an ID.
test.removeChild(test.childNodes[0]); probably doesn't work because you have some text nodes before the table.
test.removeChild(test.firstElementChild)probably will work
document.getElementById("calendar-dates").removeChild(document.getElementById('tb'))
document.querySelector('button').addEventListener('click', () => {
document.getElementById('wrapper').removeChild(document.querySelector('table'));
})
table, th, td {
border: 1px solid red;
padding: 2px
}
<div id="wrapper">
<table>
<tr>
<td>Table</td>
<td>Content</td>
</tr>
</table>
</div>
<button>Remove table</button>
Does #calendar-dates contains other html than tables? If not, you can set innerHtml to empty
var calendarDates = document.getElementById("calendar-dates");
calendarDates.innerHtml = '';
calendarDates.appendChild(calendar);

Dynamically generated table - using an array to fill in TD values

I need your help,
For some reason, I can't get the data captured in my array to populate into the TD cells of my dynamically generated table:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function addTable() {
var myTableDiv = document.getElementById("metric_results")
var table = document.createElement('TABLE')
var tableBody = document.createElement('TBODY')
table.border = '1'
table.appendChild(tableBody);
var heading = new Array();
heading[0] = "Request Type"
heading[1] = "Group A"
heading[2] = "Groub B"
heading[3] = "Group C"
heading[4] = "Total"
var stock = new Array()
stock[0] = new Array("Cars", "88.625", "85.50", "85.81", "987")
stock[1] = new Array("Veggies", "88.625", "85.50", "85.81", "988")
stock[2] = new Array("Colors", "88.625", "85.50", "85.81", "989")
stock[3] = new Array("Numbers", "88.625", "85.50", "85.81", "990")
stock[4] = new Array("Requests", "88.625", "85.50", "85.81", "991")
//TABLE COLUMNS
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (i = 0; i < heading.length; i++) {
var th = document.createElement('TH')
th.width = '75';
th.appendChild(document.createTextNode(heading[i]));
tr.appendChild(th);
}
//TABLE ROWS
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (i = 0; i < stock.length; i++) {
for (j = 0; j < stock[i].length; j++) {
var td = document.createElement('TD')
td.appendChild(document.createTextNode(stock[i][j]));
td.appendChild(td)
}
}
myTableDiv.appendChild(table)
}
</script>
</head>
<div id="metric_results">
<input type="button" id="create" value="Click here" onclick="Javascript:addTable()">
</div>
</body>
</html>
Change:
var tr = document.createElement('TR'); // this should be inside the first loop
tableBody.appendChild(tr); // this should be just before the first loop is over
for (i=0; i<stock.length; i++) {
for (j=0; j<stock[i].length; j++) {
var td = document.createElement('TD')
td.appendChild(document.createTextNode(stock[i][j]));
td.appendChild(td) // this should be tr.appendChild(td)
}
}
to this:
for (i = 0; i < stock.length; i++) {
var tr = document.createElement('TR');
for (j = 0; j < stock[i].length; j++) {
var td = document.createElement('TD')
td.appendChild(document.createTextNode(stock[i][j]));
tr.appendChild(td)
}
tableBody.appendChild(tr);
}
Fiddle

Dynamic creation of table with DOM

Can someone tell me what's wrong with this code? I want to create a table with 2 columns and 3 rows, and in the cells I want Text1 and Text2 on every row. This code creates a table with 2 columns and 3 rows, but it's only text in the cells in the third row (the others are empty).
var tablearea = document.getElementById('tablearea');
var table = document.createElement('table');
var tr = [];
var td1 = document.createElement('td');
var td2 = document.createElement('td');
var text1 = document.createTextNode('Text1');
var text2 = document.createTextNode('Text2');
for (var i = 1; i < 4; i++){
tr[i] = document.createElement('tr');
for (var j = 1; j < 4; j++){
td1.appendChild(text1);
td2.appendChild(text2);
tr[i].appendChild(td1);
tr[i].appendChild(td2);
}
table.appendChild(tr[i]);
}
tablearea.appendChild(table);
You must create td and text nodes within loop. Your code creates only 2 td, so only 2 are visible. Example:
var table = document.createElement('table');
for (var i = 1; i < 4; i++){
var tr = document.createElement('tr');
var td1 = document.createElement('td');
var td2 = document.createElement('td');
var text1 = document.createTextNode('Text1');
var text2 = document.createTextNode('Text2');
td1.appendChild(text1);
td2.appendChild(text2);
tr.appendChild(td1);
tr.appendChild(td2);
table.appendChild(tr);
}
document.body.appendChild(table);
It is because you're only creating two td elements and 2 text nodes.
Creating all nodes in a loop
Recreate the nodes inside your loop:
var tablearea = document.getElementById('tablearea'),
table = document.createElement('table');
for (var i = 1; i < 4; i++) {
var tr = document.createElement('tr');
tr.appendChild( document.createElement('td') );
tr.appendChild( document.createElement('td') );
tr.cells[0].appendChild( document.createTextNode('Text1') )
tr.cells[1].appendChild( document.createTextNode('Text2') );
table.appendChild(tr);
}
tablearea.appendChild(table);
Creating then cloning in a loop
Create them beforehand, and clone them inside the loop:
var tablearea = document.getElementById('tablearea'),
table = document.createElement('table'),
tr = document.createElement('tr');
tr.appendChild( document.createElement('td') );
tr.appendChild( document.createElement('td') );
tr.cells[0].appendChild( document.createTextNode('Text1') )
tr.cells[1].appendChild( document.createTextNode('Text2') );
for (var i = 1; i < 4; i++) {
table.appendChild(tr.cloneNode( true ));
}
tablearea.appendChild(table);
Table factory with text string
Make a table factory:
function populateTable(table, rows, cells, content) {
if (!table) table = document.createElement('table');
for (var i = 0; i < rows; ++i) {
var row = document.createElement('tr');
for (var j = 0; j < cells; ++j) {
row.appendChild(document.createElement('td'));
row.cells[j].appendChild(document.createTextNode(content + (j + 1)));
}
table.appendChild(row);
}
return table;
}
And use it like this:
document.getElementById('tablearea')
.appendChild( populateTable(null, 3, 2, "Text") );
Table factory with text string or callback
The factory could easily be modified to accept a function as well for the fourth argument in order to populate the content of each cell in a more dynamic manner.
function populateTable(table, rows, cells, content) {
var is_func = (typeof content === 'function');
if (!table) table = document.createElement('table');
for (var i = 0; i < rows; ++i) {
var row = document.createElement('tr');
for (var j = 0; j < cells; ++j) {
row.appendChild(document.createElement('td'));
var text = !is_func ? (content + '') : content(table, i, j);
row.cells[j].appendChild(document.createTextNode(text));
}
table.appendChild(row);
}
return table;
}
Used like this:
document.getElementById('tablearea')
.appendChild(populateTable(null, 3, 2, function(t, r, c) {
return ' row: ' + r + ', cell: ' + c;
})
);
You need to create new TextNodes as well as td nodes for each column, not reuse them among all of the columns as your code is doing.
Edit:
Revise your code like so:
for (var i = 1; i < 4; i++)
{
tr[i] = document.createElement('tr');
var td1 = document.createElement('td');
var td2 = document.createElement('td');
td1.appendChild(document.createTextNode('Text1'));
td2.appendChild(document.createTextNode('Text2'));
tr[i].appendChild(td1);
tr[i].appendChild(td2);
table.appendChild(tr[i]);
}
<title>Registration Form</title>
<script>
var table;
function check() {
debugger;
var name = document.myForm.name.value;
if (name == "" || name == null) {
document.getElementById("span1").innerHTML = "Please enter the Name";
document.myform.name.focus();
document.getElementById("name").style.border = "2px solid red";
return false;
}
else {
document.getElementById("span1").innerHTML = "";
document.getElementById("name").style.border = "2px solid green";
}
var age = document.myForm.age.value;
var ageFormat = /^(([1][8-9])|([2-5][0-9])|(6[0]))$/gm;
if (age == "" || age == null) {
document.getElementById("span2").innerHTML = "Please provide Age";
document.myForm.age.focus();
document.getElementById("age").style.border = "2px solid red";
return false;
}
else if (!ageFormat.test(age)) {
document.getElementById("span2").innerHTML = "Age can't be leass than 18 and greater than 60";
document.myForm.age.focus();
document.getElementById("age").style.border = "2px solid red";
return false;
}
else {
document.getElementById("span2").innerHTML = "";
document.getElementById("age").style.border = "2px solid green";
}
var password = document.myForm.password.value;
if (document.myForm.password.length < 6) {
alert("Error: Password must contain at least six characters!");
document.myForm.password.focus();
document.getElementById("password").style.border = "2px solid red";
return false;
}
re = /[0-9]/g;
if (!re.test(password)) {
alert("Error: password must contain at least one number (0-9)!");
document.myForm.password.focus();
document.getElementById("password").style.border = "2px solid red";
return false;
}
re = /[a-z]/g;
if (!re.test(password)) {
alert("Error: password must contain at least one lowercase letter (a-z)!");
document.myForm.password.focus();
document.getElementById("password").style.border = "2px solid red";
return false;
}
re = /[A-Z]/g;
if (!re.test(password)) {
alert("Error: password must contain at least one uppercase letter (A-Z)!");
document.myForm.password.focus();
document.getElementById("password").style.border = "2px solid red";
return false;
}
re = /[$&+,:;=?##|'<>.^*()%!-]/g;
if (!re.test(password)) {
alert("Error: password must contain at least one special character!");
document.myForm.password.focus();
document.getElementById("password").style.border = "2px solid red";
return false;
}
else {
document.getElementById("span3").innerHTML = "";
document.getElementById("password").style.border = "2px solid green";
}
if (document.getElementById("data") == null)
createTable();
else {
appendRow();
}
return true;
}
function createTable() {
var myTableDiv = document.getElementById("myTable"); //indiv
table = document.createElement("TABLE"); //TABLE??
table.setAttribute("id", "data");
table.border = '1';
myTableDiv.appendChild(table); //appendChild() insert it in the document (table --> myTableDiv)
debugger;
var header = table.createTHead();
var th0 = table.tHead.appendChild(document.createElement("th"));
th0.innerHTML = "Name";
var th1 = table.tHead.appendChild(document.createElement("th"));
th1.innerHTML = "Age";
appendRow();
}
function appendRow() {
var name = document.myForm.name.value;
var age = document.myForm.age.value;
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
row.insertCell(0).innerHTML = name;
row.insertCell(1).innerHTML = age;
clearForm();
}
function clearForm() {
debugger;
document.myForm.name.value = "";
document.myForm.password.value = "";
document.myForm.age.value = "";
}
function restrictCharacters(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (((charCode >= '65') && (charCode <= '90')) || ((charCode >= '97') && (charCode <= '122')) || (charCode == '32')) {
return true;
}
else {
return false;
}
}
</script>
<div>
<form name="myForm">
<table id="tableid">
<tr>
<th>Name</th>
<td>
<input type="text" name="name" placeholder="Name" id="name" onkeypress="return restrictCharacters(event);" /></td>
<td><span id="span1"></span></td>
</tr>
<tr>
<th>Age</th>
<td>
<input type="text" onkeypress="return event.charCode === 0 || /\d/.test(String.fromCharCode(event.charCode));" placeholder="Age"
name="age" id="age" /></td>
<td><span id="span2"></span></td>
</tr>
<tr>
<th>Password</th>
<td>
<input type="password" name="password" id="password" placeholder="Password" /></td>
<td><span id="span3"></span></td>
</tr>
<tr>
<td></td>
<td>
<input type="button" value="Submit" onclick="check();" /></td>
<td>
<input type="reset" name="Reset" /></td>
</tr>
</table>
</form>
<div id="myTable">
</div>
</div>
var html = "";
for (var i = 0; i < data.length; i++){
html +="<tr>"+
"<td>"+ (i+1) + "</td>"+
"<td>"+ data[i].name + "</td>"+
"<td>"+ data[i].number + "</td>"+
"<td>"+ data[i].city + "</td>"+
"<td>"+ data[i].hobby + "</td>"+
"<td>"+ data[i].birthdate + "</td>"+"<td><button data-arrayIndex='"+ i +"' onclick='editData(this)'>Edit</button><button data-arrayIndex='"+ i +"' onclick='deleteData()'>Delete</button></td>"+"</tr>";
}
$("#tableHtml").html(html);
You can create a dynamic table rows as below:
var tbl = document.createElement('table');
tbl.style.width = '100%';
for (var i = 0; i < files.length; i++) {
tr = document.createElement('tr');
var td1 = document.createElement('td');
var td2 = document.createElement('td');
var td3 = document.createElement('td');
::::: // As many <td> you want
td1.appendChild(document.createTextNode());
td2.appendChild(document.createTextNode());
td3.appendChild(document.createTextNode();
tr.appendChild(td1);
tr.appendChild(td2);
tr.appendChild(td3);
tbl.appendChild(tr);
}
when you say 'appendchild' you actually move your child from one parent to another.
you have to create a node for each cell.
In my example, serial number is managed according to the actions taken on each row using css. I used a form inside each row, and when new row created then the form will get reset.
/*auto increment/decrement the sr.no.*/
body {
counter-reset: section;
}
i.srno {
counter-reset: subsection;
}
i.srno:before {
counter-increment: section;
content: counter(section);
}
/****/
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type='text/javascript'>
$(document).ready(function () {
$('#POITable').on('change', 'select.search_type', function (e) {
var selectedval = $(this).val();
$(this).closest('td').next().html(selectedval);
});
});
</script>
<table id="POITable" border="1">
<tr>
<th>Sl No</th>
<th>Name</th>
<th>Your Name</th>
<th>Number</th>
<th>Input</th>
<th>Chars</th>
<th>Action</th>
</tr>
<tr>
<td><i class="srno"></i></td>
<td>
<select class="search_type" name="select_one">
<option value="">Select</option>
<option value="abc">abc</option>
<option value="def">def</option>
<option value="xyz">xyz</option>
</select>
</td>
<td></td>
<td>
<select name="select_two" >
<option value="">Select</option>
<option value="123">123</option>
<option value="456">456</option>
<option value="789">789</option>
</select>
</td>
<td><input type="text" size="8"/></td>
<td>
<select name="search_three[]" >
<option value="">Select</option>
<option value="one">1</option>
<option value="two">2</option>
<option value="three">3</option>
</select>
</td>
<td><button type="button" onclick="deleteRow(this)">-</button><button type="button" onclick="insRow()">+</button></td>
</tr>
</table>
<script type='text/javascript'>
function deleteRow(row)
{
var i = row.parentNode.parentNode.rowIndex;
document.getElementById('POITable').deleteRow(i);
}
function insRow()
{
var x = document.getElementById('POITable');
var new_row = x.rows[1].cloneNode(true);
var len = x.rows.length;
//new_row.cells[0].innerHTML = len; //auto increment the srno
var inp1 = new_row.cells[1].getElementsByTagName('select')[0];
inp1.id += len;
inp1.value = '';
new_row.cells[2].innerHTML = '';
new_row.cells[4].getElementsByTagName('input')[0].value = "";
x.appendChild(new_row);
}
</script>
Hope this helps.
In My example call add function from button click event and then get value from form control's and call function generateTable.
In generateTable Function check first Table is Generaed or not. If table is undefined then call generateHeader Funtion and Generate Header and then call addToRow function for adding new row in table.
<input type="button" class="custom-rounded-bttn bttn-save" value="Add" id="btnAdd" onclick="add()">
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div class="dataGridForItem">
</div>
</div>
</div>
//Call Function From Button click Event
var counts = 1;
function add(){
var Weightage = $('#Weightage').val();
var ItemName = $('#ItemName option:selected').text();
var ItemNamenum = $('#ItemName').val();
generateTable(Weightage,ItemName,ItemNamenum);
$('#Weightage').val('');
$('#ItemName').val(-1);
return true;
}
function generateTable(Weightage,ItemName,ItemNamenum){
var tableHtml = '';
if($("#rDataTable").html() == undefined){
tableHtml = generateHeader();
}else{
tableHtml = $("#rDataTable");
}
var temp = $("<div/>");
var row = addToRow(Weightage,ItemName,ItemNamenum);
$(temp).append($(row));
$("#dataGridForItem").html($(tableHtml).append($(temp).html()));
}
//Generate Header
function generateHeader(){
var html = "<table id='rDataTable' class='table table-striped'>";
html+="<tr class=''>";
html+="<td class='tb-heading ui-state-default'>"+'Sr.No'+"</td>";
html+="<td class='tb-heading ui-state-default'>"+'Item Name'+"</td>";
html+="<td class='tb-heading ui-state-default'>"+'Weightage'+"</td>";
html+="</tr></table>";
return html;
}
//Add New Row
function addToRow(Weightage,ItemName,ItemNamenum){
var html="<tr class='trObj'>";
html+="<td>"+counts+"</td>";
html+="<td>"+ItemName+"</td>";
html+="<td>"+Weightage+"</td>";
html+="</tr>";
counts++;
return html;
}
You can do that using LemonadeJS.
<html>
<script src="https://lemonadejs.net/v2/lemonade.js"></script>
<div id='root'></div>
<script>
var Component = (function() {
var self = {};
self.rows = [
{ title:'Google', description: 'The alpha search engine...' },
{ title:'Bind', description: 'The microsoft search engine...' },
{ title:'Duckduckgo', description: 'Privacy in the first place...' },
];
// Custom components such as List should always be unique inside a real tag.
var template = `<table cellpadding="6">
<thead><tr><th>Title</th><th>Description</th></th></thead>
<tbody #loop="self.rows">
<tr><td>{{self.title}}</td><td>{{self.description}}</td></tr>
</tbody>
</table>`;
return lemonade.element(template, self);
});
lemonade.render(Component, document.getElementById('root'));
</script>
</html>

Categories