Dynamically adding rows to a table - javascript

I'm trying to dynamically add a <tr> with two <td>s into a <table> via javascript, but my fiddle doesn't seem to do anything, does anyone see the problem?
Fiddle: https://jsfiddle.net/otL69Lpo/2/
HTML:
<button type="button" onclick="myFunction()">Click Me!</button>
<table class="table table-bordered" id="chatHistoryTable">
<tr>
<td>
12:30:30
</td>
<td>
text here
</td>
</table>
JS:
function myFunction() {
var table = document.getElementById("chatHistoryTable");
var tr = document.createElement("tr");
var td = document.createElement("td");
var td2 = document.createElement("td");
var txt = document.createTextNode("TIMESTAMP");
var txt2 = document.createTextNode("user: text");
td.appendChild(txt);
td2.appendChild(txt2);
tr.appendChild(td);
tr.appendChild(td2);
table.appendChild(tr);
}
Output should be as:
| TIMESTAMP | user: text |

This is a common issue in jsFiddle. There are several options for how to load the JS and you'll need to change the loading to either:
No wrap - in <head>
No wrap - in <body>

Related

Creating a timetable using JavaScript

I am trying to create a web page where user can create his own schedule. User can enter the values of lines and columns in some input to build a table in which the user will write his schedule. I use this javascript code:
var p = document.getElementById('paragraph');
var table = document.createElement('table');
var tbody = document.createElement('tbody');
table.appendChild(tbody);
for (let i = 0; i < lines; i++){
let tr = document.createElement('tr');
for (let j = 0; j < columns; j++){
let td = document.createElement('td');
}
tbody.appendChild(tr);
}
p.appendChild(table);
However, when I'am trying to add information to table cells, I can't write values to each of them. I've used .innerHTML but it doesn't work the way it needs to. The information will be written only to the beginning of the table.
Should I give id to each td and then address to them by id when I need to write the information? Or there is another way to write values to table cells?
I think you need something like this to insert the data.
We have insertRow(), which is pre-defined function which i used in this answer to insert new row and then inserted columns in it with insertCell function.
<!DOCTYPE html>
<html>
<body>
<div class="inputs">
<input type="text" id="input1" placeholder="Enter first col data" >
<input type="text" id="input2" placeholder="Enter second col data" >
</div>
<br> <br> <br>
<table id="myTable">
<thead style="background-color: beige;">
<tr>
<td>default head row cell 1</td>
<td>default head row cell 2</td>
</tr>
</thead>
<tbody></tbody>
</table>
<br>
<button type="button" onclick="myFunction()">add data to body row</button>
<script>
function myFunction() {
var table = document.querySelector("#myTable tbody");
var row = table.insertRow();
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
const val1 = document.getElementById('input1').value;
const val2 = document.getElementById('input2').value;
cell1.innerHTML = val1;
cell2.innerHTML = val2;
}
</script>
</body>
</html>
I think that you need to refer to your button in the js file and write a function that will be executed on the "onclick" event
In this function, you are accessing the table variable. By using the built in javaScript function «insertRow()» you are adding rows to your table. Then you should add cells to this row in which information that users entered will be stored. This you can also do by using build in function «insertCell()»
Next, you access the fields in which the user has entered data
Retrieve values ​​using the «value» built-in function
Using the built-in «innerHTML» function, draw cells with the information that you received in the previous step
You can look at the written code below for better assimilation of information
<!DOCTYPE html>
<html>
<body>
<div class="inputs" >
<input type="text" id="firstColumn" placeholder="Enter data here" >
<input type="text" id="SecondColumn" placeholder="Enter data here" >
</div>
<table id="Table">
<thead>
<tr>
<td style="background-color: pink;">Name of first column</td>
<hr>
<td style="background-color: purple;">Name of second column</td>
</tr>
</thead>
<tbody></tbody>
</table>
<br>
<button style="background-color: yellow;" type="button" id = "btn">Add</button>
<script>
const button = document.querySelector('#btn');
btn.onclick = function() {
var table = document.querySelector("#Table tbody");
var row = table.insertRow();
var Fcell = row.insertCell(0);
var Scell = row.insertCell(1);
const Fdata = document.getElementById('firstColumn').value;
const Sdata = document.getElementById('SecondColumn').value;
Fcell.innerHTML = Fdata;
Scell.innerHTML = Sdata;
}
</script>
</body>
</html>

What is the tag in HTML that refer to element in DOM?

In line8:- it has element.parentElement.remove(element), here the element it refers to what tag in HTML?
Note:- This the fiddle code, in case you need it.
Javascript
var td4 = document.createElement('td');
td4.setAttribute("id", "td4");
td4.innerHTML = <button
onclick=remove(this.parentElement)>X</button> *line4
tr.appendChild(td4);
function remove(element){
element.parentElement.remove(element) **line8**
}
HTML
<div class='table'>
<table id="table">
<th>
<tr>
<td>Task</td>
<td>Date</td>
<td>Urgency</td>
<td>Done</td>
</tr>
</th>
<button onclick=clearAll()> Clear All </button>
</table>
</div>
You should use template strings.
// You'll need to access to the tr element.
// Also, I would recommend use const instead of var
const tr = document.querySelector('tr');
const td4 = document.createElement('td');
td4.setAttribute("id", "td4");
// You'll need to use the parentElement property twice, because the button will be inserted into the 'td' and you need access to the 'tr'
td4.innerHTML = `<button
onclick=remove(this.parentElement.parentElement)>X</button>`
tr.appendChild(td4);
function remove(element){
element.parentElement.remove(element)
}
<div class='table'>
<table id="table">
<th>
<tr>
<td>Task</td>
<td>Date</td>
<td>Urgency</td>
<td>Done</td>
</tr>
</th>
<button onclick=clearAll()> Clear All </button>
</table>
</div>
Read more about Accessing the DOM here.
element in element.parentElement.remove(element) is td4.
You should add console to print the tag easily.
function remove(element){
console.log(element);
element.parentElement.remove(element) **line8**
}

Adding elements with JavaScript

I want to add a new row to a table. Therefore I have tried it in two different ways. In my opinion both should work. But indeed the don't. The first approach does not work. But why?
First approach (not working...):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Table</title>
<script type="text/javascript">
function addLine(nr, name, date) {
var neueZeile = document.createElement("tr");
var neuerEintrag1 = document.createElement("td");
var neuerText1 = document.createTextNode(nr);
var neuerEintrag2 = document.createElement("td");
var neuerText2 = document.createTextNode(name);
var neuerEintrag3 = document.createElement("td");
var neuerText3 = document.createTextNode(date);
neuerEintrag1.appendChild(neuerText1);
neuerEintrag2.appendChild(neuerText2);
neuerEintrag3.appendChild(neuerText3);
neueZeile.appendChild(neuerEintrag1);
neueZeile.appendChild(neuerEintrag2);
neueZeile.appendChild(neuerEintrag3);
var parentN = document.getElementById("myTable");
parentN.appendChild(neueZeile);
</script>
<link rel="stylesheet" type="text/css" href="Website.css" />
</head>
<body>
<table class="table" id="myTable">
<thead>
<td>Nr.</td>
<td>Name</td>
<td>Datum</td>
</thead>
<tr>
<td>1</td>
<td>Max</td>
<td>01.01.2001</td>
</tr>
</table>
<form name=addRow>
Nr.:
<input type=text name=btn1>
Name:
<input type=text name=btn2>
Date:
<input type=text name=btn3>
<input type=button name=btn4 value=ADD
onclick="addLine(btn1.value,btn2.value,btn3.value)">
</form>
<input type=button name=btn5 value=DeleteLastAddedRow onclick="deleteRow()">
<a class="back" href="Website.html">Zurück</a>
</body>
</html>
My approach is not working. Does somebody know why or can help me?
Second approach (works fine...):
function addLine(nr, name, date) {
var table = document.getElementById("myTable");
var row = table.insertRow();
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
cell1.innerHTML = nr;
cell2.innerHTML = name;
cell3.innerHTML = date;
}
I am really interested in why the the first approach is not working.
Does somebody have an idea?
Kind regards
You missed to create tr element. Create tr and append it to table then all td to new tr.
Here is working code
function addLine(nr, name, date) {
var neuerEintrag1 = document.createElement("td");
var neuerText1 = document.createTextNode(nr);
var neuerEintrag2 = document.createElement("td");
var neuerText2 = document.createTextNode(name);
var neuerEintrag3 = document.createElement("td");
var neuerText3 = document.createTextNode(date);
neuerEintrag1.appendChild(neuerText1);
neuerEintrag2.appendChild(neuerText2);
neuerEintrag3.appendChild(neuerText3);
var parentN = document.getElementById("myTable");
var row = document.createElement("tr");
parentN.appendChild(row);
row.appendChild(neuerEintrag1);
row.appendChild(neuerEintrag2);
row.appendChild(neuerEintrag3);
}
<table class="table" id="myTable">
<thead>
<td>Nr.</td>
<td>Name</td>
<td>Datum</td>
</thead>
<tr>
<td>1</td>
<td>Max</td>
<td>01.01.2001</td>
</tr>
</table>
<form name=addRow>
Nr.:
<input type=text name=btn1> Name:
<input type=text name=btn2> Date:
<input type=text name=btn3>
<input type=button name=btn4 value=ADD onclick="addLine(btn1.value,btn2.value,btn3.value)">
</form>

how to use getElementById to get the table specified with id

i want to use js to add one row in an exsiting table,however i got an error:document.getElementById() is null,here is my code:
<!DOCTYPE html>
<html>
<head>
<title>use js to create one row</title>
</head>
<body >
<tr id="table">
<td>row 1</td>
</tr>
<script>
window.onload = function(){
var td = document.createElement("td");
td.innerHTML = "add row";
var tr = document.getElementById("table");
tr.appendChild(rows);
}
</script>
</body>
</html>
Because tr is invalid outside of a table, the browser is basically ignoring the tr element entirely and just putting the text row 1 directly in body, which is why getElementById didn't return an element; it was never created by the browser when parsing the HTML.
Put the tr in a table (and ideally in a tbody):
<table>
<tbody id="tbody">
<tr>
<td>row 1</td>
</tr>
</tbody>
</table>
and append to the tbody, being sure to create a row (tr) as well as a td since your apparent goal is to add a row:
var td = document.createElement("td");
td.innerHTML = "add row";
var tr = document.createElement("tr");
tr.appendChild(td);
document.getElementById("tbody").appendChild(tr);
It's also almost never useful to use the load event on window. Instead, just put your script at the very end of the HTML, just before the closing </body> tag.
Live example:
<table>
<tbody id="tbody">
<tr>
<td>row 1</td>
</tr>
</tbody>
</table>
<script>
(function() {
var td = document.createElement("td");
td.innerHTML = "add row";
var tr = document.createElement("tr");
tr.appendChild(td);
document.getElementById("tbody").appendChild(tr);
})();
</script>

Create div within a cell in Javascript

I am having troubles creating a div after creating a cell dynamically using Javascript. My goal is to be able to add the exact same original table row and its contents below. Below is the HTML code:
<table width="100%" id="processTable">
<tr>
<td id="ProcessDetails"><div id="description">Replace with description.</div>
<div id="QuestionToAnswer"><b>Replace with a question answerable by YES or NO</b></div>
</td>
<td id="AvailableAnswersColumn">
<p id="option1">YES</p>
<p id="option2">NO: Proceed to next question</p>
</td>
</tr>
<!--Insert new table row if needed-->
</table>
<div id="footer">
<input type="button" value="Insert Table Row" id="CreateRow" class="CreateRow" onclick="insertRow()" />
</div>
Here is the Javascript
<script>
function insertRow() {
var table = document.getElementById("processTable");
var row = table.insertRow(1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = //within this cell should be created the div ids "description" + "QuestionToAnswer";
cell2.innerHTML = //within this cell should be created the paragraph with ids "option1" + "option2";;
cell1.setAttribute("id", "ProcessDetails", 0);
cell2.setAttribute("id", "AvailableAnswersColumn", 1);
}
</script>
Please help.
document.createElement will be your friend here.
var div = document.createElement("div");
div.innerHTML = "Replace with description.";
cell1.appendChild(div);
With document.createElement(<tagname>) you can create any html element you want with JavaScript code. You can append it to the cell by using appendChild. Since div in my example is an object and a reference to a DOM node after it gets appended you can set event handlers to it etc.

Categories

Resources