JavaScript Error...Not creating elements when the button is clicked - javascript

My code look like this, It should have created a table when the "submitButton" was clicked but it doesn't do so. Here is my code:
submitButton.addEventListener("click", () => {
var newTable = document.createElement("table");
for(let i = 0; i < parseInt(numOfStudents); i++){
var newRow = document.createElement("tr");
var newInput = document.createElement("td");
var newInput2 = document.createElement("td");
document.newRow.appendChild(newInput);
document.newRow.appendChild(newInput2);
document.newTable.appendChild(newRow);
document.body.appendChild(newTable);
}
});

You can't access elements with body. you need to use DOM functions like getElementById etc.. if its a new created elements as in your loop you can append to them directly as below
var numOfStudents=10
submitButton=document.getElementById("submitButton")
submitButton.addEventListener("click", () => {
var newTable = document.createElement("table");
for(let i = 0; i < parseInt(numOfStudents); i++){
var newRow = document.createElement("tr");
var newInput = document.createElement("td");
var newInput2 = document.createElement("td");
newRow.appendChild(newInput);
newRow.appendChild(newInput2);
newTable.appendChild(newRow);
document.body.appendChild(newTable);
}
});
<button id="submitButton" >button</button>

U just need to add some text into it..otherwise you won't see it (unless you open the dev console).
Here is an example:
// Helpers
const createElement = el => document.createElement(el)
const createText = text => document.createTextNode(text)
// Create rows
const addStudentRows = students => {
const $body = document.querySelector('body')
const $table = createElement('table')
for (let i = 0; i < students;i++ ) {
let $td1 = createElement('td')
let $td2 = createElement('td')
$td1.appendChild(createText('Hello'))
$td2.appendChild(createText('World'))
let $tr = createElement('tr')
$tr.appendChild($td1)
$tr.appendChild($td2)
$table.appendChild($tr)
}
$body.appendChild($table)
}
// Event listener
document.querySelector('button')
.addEventListener('click', e => addStudentRows(1))
table {
margin-bottom: 10px;
}
table tr td {
padding: 10px;
border-right:1px solid #f0f0f0;
border-top: 1px solid #f0f0f0;
border-bottom: 1px solid #f0f0f0;
}
table tr td:first-child {
border-left:1px solid #f0f0f0;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<button>Click here</button>
</body>
</html>

Related

Making a HTML table using Javascript

My data is this:
var manholeInfo = [{name: "manhole", date_key: "date"}]
I would like to make a table like this picture:
But it comes out like this:
Code:
var iwContent = document.createElement("div");
iwContent.className = 'infowindow';
iwContent.setAttribute('style', "width:160px;text-align:center;padding:5px");
var manholeInfo = [{
name: "manhole",
date_key: "2020-10-29"
}]
var table = document.createElement('table');
for (let element of manholeInfo) {
let row = table.insertRow();
for (let key in element) {
let column = row.insertCell();
column.innerHTML = element[key];
}
}
iwContent.appendChild(table);
document.body.appendChild(iwContent);
Place the table.insertRow inside the inner for loop, and create separate cells for each key/value:
var iwContent = document.createElement("div");
iwContent.className = 'infowindow';
iwContent.setAttribute('style', "width:160px; text-align:center; padding:5px");
var manholeInfo = [{
name: "manhole",
date_key: "2020-10-29"
}]
var table = document.createElement('table');
for (let element of manholeInfo) {
for (let key in element) {
let row = table.insertRow();
let columnKey = row.insertCell();
let columnValue = row.insertCell();
columnKey.innerHTML = key;
columnValue.innerHTML = element[key];
}
}
iwContent.appendChild(table);
document.body.appendChild(iwContent);
var iwContent = document.createElement("div");
iwContent.className = 'infowindow';
iwContent.setAttribute('style', "width:250px; text-align:center; padding:5px");
var manholeInfo = [{
name: "manhole",
date_key: "2020-10-29"
}]
var table = document.createElement('table');
for (var i = 0; i < manholeInfo.length; i++) {
var child = manholeInfo[i];
Object.keys(child).forEach(function (k) {
// console.log(k);
var row = table.insertRow();
var cell_1 = row.insertCell();
var cell_2 = row.insertCell();
cell_1.appendChild(document.createTextNode(k));
cell_2.appendChild(document.createTextNode(child[k]));
})
}
iwContent.appendChild(table);
document.body.appendChild(iwContent);
td {
border: solid 1px #ddd;
border-collapse: collapse;
padding: 5px 6px;
text-align: center;
font-weight: bold;
}

How to overwrite data in a table?

Trying to create a table with data-attributes when clicking on a link
The problem is most likely in this code
I can not understand how to rewrite the data in the table.
Now the data is sequentially added to the table.
My code - https://jsfiddle.net/347x8bwq/
(function() {
'use strict';
function createTable() {
let link = document.querySelectorAll('.link');
let block = document.querySelector('.block');
let blockTable = document.querySelector('.table');
for (let i = 0; i < link.length; i++) {
let links = link[i];
links.addEventListener('click', function(e) {
e.preventDefault();
let linkData = this.dataset;
for (let j in linkData) {
let tableRow = document.createElement('tr');
let arr = linkData[j].split('|');
for (let k = 0; k < arr.length; k++) {
let tableCol = document.createElement('td');
tableCol.innerHTML = arr[k];
tableRow.appendChild(tableCol);
}
blockTable.appendChild(tableRow);
}
});
}
}
createTable();
Desired behavior - when clicking on a link each time - a new table was created
Before you append your tableRow to the blockTable, clear its innerHTML.
(function() {
'use strict';
function createTable() {
let link = document.querySelectorAll('.link');
let block = document.querySelector('.block');
let blockTable = document.querySelector('.table');
for (let i = 0; i < link.length; i++) {
let links = link[i];
links.addEventListener('click', function(e) {
e.preventDefault();
let linkData = this.dataset;
blockTable.innerHTML = "";
for (let j in linkData) {
let tableRow = document.createElement('tr');
let arr = linkData[j].split('|');
for (let k = 0; k < arr.length; k++) {
let tableCol = document.createElement('td');
tableCol.innerHTML = arr[k];
tableRow.appendChild(tableCol);
}
blockTable.appendChild(tableRow);
}
});
}
}
createTable();
})();
.table {
width: 100%;
table-layout: fixed;
}
td {
border: 1px solid #ccc;
}
.link {
display: block;
margin-bottom: 5px;
}
.block {
padding: 25px;
border: 1px solid #000;
}
Link 1
Link 2
Link 3
<div class="block">
<table class="table">
<tr>
<td>Атрибут1</td>
<td>Title</td>
</tr>
<tr>
<td>Атрибут2</td>
<td>Subtitle</td>
</tr>
<tr>
<td>Атрибут3</td>
<td>1234</td>
</tr>
</table>
</div>
See - https://jsfiddle.net/2wvm6de8/
You have to clear the table before adding a new elements. Just add blockTable.innerHTML = ''; after e.preventDefault();
https://jsfiddle.net/vLm60kzq/

Create Recursive Form Elements

I'm creating a homework calculator. I need to recursively create form elements, and found out how to make a recursively creating table. How do I turn the spaces in that table into form elements that create themselves recursively? If this isn't clear, please tell me.
<table id="xTable"></table>
<script>
var rQty = parseInt(prompt("Number of Rows"), 10);
var cQty = parseInt(prompt("Number of Columns"), 10);
var table = document.getElementById("xTable");
for (let i = 0; i < rQty; i++) {
var row = table.insertRow();
for (let j = 0; j < cQty; j++) {
var cell = row.insertCell();
cell.textContent = "I want to make this into a recursive form creator ";
}
}
</script>
<style>
td {
border: 2px ridge #333;
text-align: center;
}
</style>
It's rather simple, just create the elements you want to insert into the cells with document.createElement, then set the properties you want them to have and use cell.appendChild to place them into the cell.
This example creates <input type="text"> elements:
var rQty = parseInt(prompt("Number of Rows"), 10);
var cQty = parseInt(prompt("Number of Columns"), 10);
var table = document.getElementById("xTable");
for (let i = 0; i < rQty; i++) {
var row = table.insertRow();
for (let j = 0; j < cQty; j++) {
var cell = row.insertCell();
var input = document.createElement('input');
input.type = 'text';
input.name = 'input_r' + i + '-c' + j;
cell.appendChild(input);
}
}
td {
border: 2px ridge #333;
text-align: center;
}
<table id="xTable"></table>

How to change child classes by changing only the parent class?

I have a table with black and white cells and I want to create a button which changes the colors of cells.
I have done it by using for loop jsfiddle.net
Now, I dont want to use the function below. Is it possible to change only the class atribute of whole table to change class of all td tag's?
function changeClors() {
var cells = document.getElementsByTagName('td');
for (var i = 0; i < cells.length; i++) {
cSwap(cells[i])
}
Yes it's possible you just need a css class for the table to do it and a function to toggle this class with your table.
This is how should be your css defined:
.myTable td{
background: gray;
}
And this is the JS function to toggle it in the table:
function toggleClass(){
var table = document.querySelector("table");
if(table.className !== "myTable"){
table.className = "myTable";
}else{
table.className = '';
}
}
Demo:
This is an updated Demo:
function cSwap(cell) {
if (cell.className == "t")
cell.className = "t2";
else if (cell.className == "t2")
cell.className = "t";
}
function tableCreate(n) {
var body = document.getElementsByTagName('body')[0];
var tbl = document.createElement('table');
tbl.setAttribute('onclick', 'cSwap(event.target)');
for (var i = 0; i < n; i++) {
var tr = document.createElement('tr');
for (var j = 0; j < n; j++) {
var td = document.createElement('td');
tr.appendChild(td)
td.classList.add('t');
}
tbl.appendChild(tr);
}
body.appendChild(tbl);
}
function changeClors() {
var cells = document.getElementsByTagName('td');
for (var i = 0; i < cells.length; i++) {
cSwap(cells[i])
}
}
tableCreate(5);
function toggleClass() {
var table = document.querySelector("table");
if (table.className !== "myTable") {
table.className = "myTable";
} else {
table.className = '';
}
}
td {
border: 1px solid black;
border-collapse: collapse;
padding: 28px;
}
.t {
background: white
}
.t2 {
background: black
}
.myTable td {
background: gray;
}
<body>
<input type="button" value="Change colors" onclick="changeClors()">
<input type="button" value="Change table" onclick="toggleClass()">
</body>
Instead of using the for loop, try toggling the invert class name on the table element. Then adjust the css accordingly, as in the snippet below:
function cSwap(cell) {
if (cell.className == "t")
cell.className = "t2";
else if (cell.className == "t2")
cell.className = "t";
}
function tableCreate(n) {
var body = document.getElementsByTagName('body')[0];
var tbl = document.createElement('table');
tbl.setAttribute('onclick', 'cSwap(event.target)');
tbl.setAttribute('id', 'myTable');
for (var i = 0; i < n; i++) {
var tr = document.createElement('tr');
for (var j = 0; j < n; j++) {
var td = document.createElement('td');
tr.appendChild(td)
td.classList.add('t');
}
tbl.appendChild(tr);
}
body.appendChild(tbl);
}
function changeClors() {
var table = document.getElementById('myTable');
table.classList.toggle('invert')
}
tableCreate(5);
td {
border: 1px solid black;
border-collapse: collapse;
padding: 28px;
}
.t {
background: white
}
.t2 {
background: black
}
.invert .t {
background: black
}
.invert .t2 {
background: white
}
<body>
<input type="button" value="Change colors" onclick="changeClors()">
</body>
If you're looking to just change the colors of the cells, you could toggle the class of the table and then use CSS selectors on the cells like the following:
.table-dark td { background-color: #000; }
.table-light td { background-color: #fff; }

i want to create table dynamically in a specific position of the html page

i am trying to create the table using js in a specific location of the page
i m getting the output but also getting an error undefind before the result
before the table creation an error is shown undefine any solution for this
<script>
function tab()
{
var x=4;
function tabb(){
var table = document.createElement('table');
table.id="a-table";
for (var i = 1; i < x; i++){
var tr = document.createElement('tr');
tr.id="myrow";
var td1 = document.createElement('td');
var td2 = document.createElement('td');
tr.appendChild(td1);
tr.appendChild(td2);
table.appendChild(tr);
}
document.body.appendChild(table);
}
document.getElementById("tab").innerHTML=tabb();
var cells = document.getElementById("a-table").getElementsByTagName("td");
var i=0;
for(i = 0; i < x+1; i++){
var cell = cells[i];
cell.innerHTML = "<img class=img1 src=faculty/comm/"+i+".jpg>";
}
}
</script>
<style>
td {
border: solid 1px #000;
border-style: none solid solid none;
padding: 10px;
border-radius:8px;
}
</style>
<body>
<input type=button onclick="tab()" value="create">
<div id="tab"></div>
</body>
Even though this will remove the undefined from the page, I strongly recommend you to consider more clean, optimized tab function.
function tab()
{
var x=4;
var table = document.createElement('table');
table.id="a-table";
for (var i = 0; i < x; i++){
var tr = document.createElement('tr');
tr.id="myrow";
var td1 = document.createElement('td');
var td2 = document.createElement('td');
tr.appendChild(td1);
tr.appendChild(td2);
table.appendChild(tr);
}
document.getElementById("tab").appendChild(table);
var cells = document.getElementById("a-table").getElementsByTagName("td");
var i=0;
for(i = 0; i < x+1; i++){
var cell = cells[i];
cell.innerHTML = "<img class=img1 src=faculty/comm/"+i+".jpg>";
}
}
td {
border: solid 1px #000;
border-style: none solid solid none;
padding: 10px;
border-radius:8px;
}
<input type=button onclick="tab()" value="create">
<div id="tab"></div>

Categories

Resources