Dynamic table with bootstrap - javascript

I'm trying to do dynamic table with bootstrap but I can't deduce why it's not working. There's a HTML part:
<div class="container">
<button onclick="CreateTable()">Extend</button>
<table class="table">
<thead>
<tr>
<th>Employee Id</th>
<th>Name</th>
<th>Country</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>John Doe</td>
<td>Country1</td>
</tr>
<tr>
<td>2</td>
<td>Mary Moe</td>
<td>Country2</td>
</tr>
<tr>
<td>3</td>
<td>Jack Dooley</td>
<td>Country3</td>
</tr>
<p id="id_tabela"></p>
</tbody>
</table>
</div>
and there's javascript:
function CreateTable() {
var employee = new Array();
employee.push([4, "Billie Jean", "Country4"]);
employee.push([5, "Harish Kumar", "Country5"]);
employee.push([6, "Pankaj Mohan", "Country6"]);
employee.push([7, "Nitin Srivastav", "Country7"]);
employee.push([8, "Ramchandra Verma", "Country8"]);
var tablecontents = "";
for (var i = 0; i < employee.length; i++) {
tablecontents += "<tr>";
for (var j = 0; j < employee[i].length; j++) {
tablecontents += "<td>" + employee[i][j] + "</td>";
}
tablecontents += "</tr>";
}
document.getElementById("id_tabela").innerHTML = tablecontents;
}
So I want to extend the table and I can't figure out why it's not working.

You are loading the data inside the paragraph, which is not what you want to do. Also the paragraph shouldn't be there. You can add an id to tbody and then just extend its innerHTML like so: https://jsfiddle.net/14pt76wp/.
Why are you using native functions? bootstrap has jQuery included. You could do something like:
$('table tbody').append(tablecontents);
Another trick:
Iterate over the array and do employee[i] = '<td>' + employee[i].join('</td><td>') + '</td>';
tablecontents = '<tr>' + employee.join('</tr><tr>') + '</tr>';

Related

delete row in table from firestore database

I am trying to create a button to delete a row in my table from the firebase database but I am not sure how to choose one specific row to delete using a button function. I am using javascript and firesource.
The function that i am using to fill my table is
function filled_table_start(num){
document.getElementById("tbody1").innerHTML = "";
members.forEach((member) => {
if(member.exists()){
row += '<tr id="student'+ (count+1) +'" >';
row += '<td>' + (count+1) +'</td>';
row += '<td>' + member.data().studentID + '</td>';
row += '<td>' + member.data().name + '</td>';
row += '<td>' + member.data().gender + '</td>';
row += '<td>' + member.data().schoolEmailAdd + '</td>';
row += '<td>' + member.data().handphoneNum + '</td>';
row += '<td><button type="button" onclick= "' + deleteDoc(doc(db,this.studentID ))+'" >Delete User</td>';
//row += '<td>' +
row += '</tr>';
document.getElementById('tbody1').innerHTML += row;
count ++;
};
});
}
I am wondering if something like this.deleteDoc will work? or is there another function that can be used to delete a specific row?
I just created a dummy demo table here. What I did is, simply give a class to each of the buttons, when you will click on the button, It will find the closest tr and remove it.
$("#tbody1").on('click', '.deleteDoc', function () {
$(this).closest('tr').remove();
});
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tbody id="tbody1">
<tr>
<th>Sl</th>
<th>ID</th>
<th>Name</th>
<th>Gender</th>
<th>Mail</th>
<th>Mobile</th>
<th>Action</th>
</tr>
<tr id="student1">
<td>1</td>
<td>11</td>
<td>ABC</td>
<td>F</td>
<td>abc#gmail.com</td>
<td>123456</td>
<td><button type="button" class="deleteDoc"> Delete User </td>
</tr>
<tr id="student2">
<td>2</td>
<td>12</td>
<td>DEF</td>
<td>M</td>
<td>def#gmail.com</td>
<td>123456</td>
<td><button type="button" class="deleteDoc"> Delete User </td>
</tr>
<tr id="student3">
<td>3</td>
<td>13</td>
<td>IJK</td>
<td>F</td>
<td>ijk#gmail.com</td>
<td>123456</td>
<td><button type="button" class="deleteDoc"> Delete User </td>
</tr>
</tbody>
</table>

HTML CSS how to make a dynamic multicolumn table from a 2D table with JavaScript

I would like to make a dynamic multicolumn table from a static 2D table, like the picture below (see solution):
The correct HTML-code as folows:
<div class="container">
<table border='1' id='theTable'>
<thead>
<tr>
<th>Name</th>
<th>Role</th>
</tr>
</thead>
<tbody>
<tr>
<td>Adam</td>
<td>AAA</td>
</tr>
<tr>
<td>Adam</td>
<td>BBB</td>
</tr>
<tr>
<td>Adam</td>
<td>CCC</td>
</tr>
<tr>
<td>Bert</td>
<td>AAA</td>
</tr>
<tr>
<td>Bert</td>
<td>CCC</td>
</tr>
<tr>
<td>Cesar</td>
<td>BBB</td>
</tr>
</tbody>
</table>
<br>
<table id='newTable' border='1'>
<thead></thead>
<tbody></tbody>
</table>
</div>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
$(document).ready(function () {
var role_arr = [];
$("#theTable td:nth-child(2)").each(function() {
if ($.inArray($(this).text(), role_arr) == -1)
role_arr.push($(this).text());
});
role_arr.sort()
console.log(role_arr);
// create thead row and put Roles in it
var trow = "<tr>";
trow += '<th>Name</th>';
for (var i=0; i<role_arr.length; i++) {
trow +='<th>'+ role_arr[i] +'</th>';
}
trow += '</tr>';
$("#newTable").find("thead").append(trow);
// create all names array
var name_arr = [];
$("#theTable td:nth-child(1)").each(function() {
if ($.inArray($(this).text(), name_arr) == -1)
name_arr.push($(this).text());
});
console.log(name_arr);
for (var i=0; i<name_arr.length; i++) {
// create an array for each name's roles
var row_arr = [];
$("#theTable tr:has(td:contains('"+name_arr[i]+"'))").each(function () {
//console.log($(this).find('td:nth-child(2)').text());
row_arr.push($(this).find('td:nth-child(2)').text());
});
// create the table body row row
var trow = "<tr>";
trow += '<td>'+name_arr[i]+'</td>';
for(var j=0; j<role_arr.length; j++) {
if(row_arr.includes(role_arr[j])) {
trow += '<td> X </td>';
}
else {
trow += '<td> - </td>';
}
}
trow += '</tr>';
$("#newTable").find("tbody").append(trow);
}
});
</script>
I used jquery to iterate through the table. First created all different roles array and then individual names array. Then created individual rows for each names. I have added comments in the code.
<div class="container">
<table border='1' id='theTable'>
<thead>
<tr>
<th>Name</th>
<th>Role</th>
</tr>
</thead>
<tbody>
<tr>
<td>Adam</td>
<td>AAA</td>
</tr>
<tr>
<td>Adam</td>
<td>BBB</td>
</tr>
<tr>
<td>Adam</td>
<td>CCC</td>
</tr>
<tr>
<td>Bert</td>
<td>AAA</td>
</tr>
<tr>
<td>Bert</td>
<td>CCC</td>
</tr>
<tr>
<td>Cesar</td>
<td>BBB</td>
</tr>
</tbody>
</table>
<br>
<table id='newTable' border='1'>
<thead></thead>
<tbody></tbody>
</table>
</div>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
$(document).ready(function () {
var role_arr = [];
$("#theTable td:nth-child(2)").each(function() {
if ($.inArray($(this).text(), role_arr) == -1)
role_arr.push($(this).text());
});
console.log(role_arr);
// create thead row and put Roles in it
var trow = "<tr>";
trow += '<th>Name</th>';
for (var i=0; i<role_arr.length; i++) {
trow +='<th>'+ role_arr[i] +'</th>';
}
trow += '</tr>';
$("#newTable").find("thead").append(trow);
// create all names array
var name_arr = [];
$("#theTable td:nth-child(1)").each(function() {
if ($.inArray($(this).text(), name_arr) == -1)
name_arr.push($(this).text());
});
console.log(name_arr);
for (var i=0; i<name_arr.length; i++) {
// create an array for each name's roles
var row_arr = [];
$("#theTable tr:has(td:contains('"+name_arr[i]+"'))").each(function () {
//console.log($(this).find('td:nth-child(2)').text());
row_arr.push($(this).find('td:nth-child(2)').text());
});
// create the table body row row
var trow = "<tr>";
trow += '<td>'+name_arr[i]+'</td>';
for(var j=0; j<role_arr.length; j++) {
if(row_arr.includes(role_arr[j])) {
trow += '<td> X </td>';
}
else {
trow += '<td> - </td>';
}
}
trow += '</tr>';
$("#newTable").find("tbody").append(trow);
}
});
</script>

Populating local storage data to an HTML table?

After creating a game and implementing scores etc, I have saved the current logged in player's username along with his score to local storage.
/*Saves current logged in player to local storage*/
let player = sessionStorage.getItem("loggedInUsername");
function savePlayer(){
/*sets logged in player + score + time*/
let Player = [player, score];
localStorage.setItem("Player",Player.toString());
}
I then call the function once the game is over. I have also created a high score table in HTML like so:
<body class = "score">
<article>
<!-- Table for TopScores -->
<table align = "center">
<tr>
<td id= "title" colspan = "3"><h1>Top Scores</h1></td>
</tr>
<tr>
<th>Username</th>
<th>Score</th>
<th>Time</th>
</tr>
<tr>
<td></td>
<td></td>
<td>0</td>
</tr>
<tr>
<td></td>
<td></td>
<td>0</td>
</tr>
<tr>
<td></td>
<td></td>
<td>0</td>
</tr>
</table>
</article>
</body>
I am having difficulty calling the player's username and his score to the high score table using localStorage.getItem.
Any help would be much appreciated.
You can create table row data from javascript, find below code snippet of jsfiddle link (https://jsfiddle.net/59u4ba0d/):
HTML:
<table>
<tbody id="tbody"></tbody>
</table>
Javascript:
var testObject = [{ 'name': 'James', 'score': 90, 'time': '16:00' }, {
'name': 'Robert', 'score': 80, 'time': '15:00' }];
localStorage.setItem('testObject', JSON.stringify(testObject));
var retrievedObject = JSON.parse(localStorage.getItem('testObject'));
var tbody = document.getElementById('tbody');
for (var i = 0; i < retrievedObject.length; i++) {
var tr = "<tr>";
tr += "<td>Name</td>" + "<td>" + retrievedObject[i].name + "</td></tr>";
tr += "<td>Score</td>" + "<td>" + retrievedObject[i].score + "</td></tr>";
tr += "<td>Time</td>" + "<td>" + retrievedObject[i].time + "</td></tr>";
tbody.innerHTML += tr;
}

Convert array of objects into HTML table with jQuery or Javascript

How can I convert the following Javascript array of object
[{"firstName":"John", "last Name":"Doe", "age":"46"},
{"firstName":"James", "last Name":"Blanc", "age":"24"}]
Into HTML table like below
<table>
<tr>
<th>firstName</th>
<th>last Name</th>
<th>age</th>
</tr>
<tr>
<td>John</td>
<td>Doe</tD>
<td>46</th>
</tr>
<tr>
<td>James</td>
<td>Blanc</tD>
<td>24</th>
</tr>
</table>
Thanks in advance.
You can do this using forEach method , which accepts as parameter a callback provided function.
var users=[{"firstName":"John", "last Name":"Doe", "age":"46"},
{"firstName":"James", "last Name":"Blanc", "age":"24"}]
users.forEach(function(item){
$('tbody').append('<tr><td>'+item.firstName+'</td><td>'+item["last Name"]+'</td><td>'+item.age+'</td></tr>')
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>firstName</th>
<th>last Name</th>
<th>age</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Try this code:
var rows = [{"firstName":"John", "last Name":"Doe", "age":"46"},
{"firstName":"James", "last Name":"Blanc", "age":"24"}];
var html = '<table>';
html += '<tr>';
for( var j in rows[0] ) {
html += '<th>' + j + '</th>';
}
html += '</tr>';
for( var i = 0; i < rows.length; i++) {
html += '<tr>';
for( var j in rows[i] ) {
html += '<td>' + rows[i][j] + '</td>';
}
html += '</tr>';
}
html += '</table>';
document.getElementById('container').innerHTML = html;
<div id="container">
</div>
In your HTML put below code
<div id="myTable">
</div>
And in script put below code
var arrObj = [{"firstName":"John", "lastName":"Doe", "age":"46"},
{"firstName":"James", "lastName":"Blanc", "age":"24"}]
var objLength = arrObj.length;
var myvar = '<table>'+
'<tr>'+
'<th>firstName</th>'+
'<th>last Name</th>'+
'<th>age</th>'+
'</tr>';
for(var i = 0; i < objLength; i++){
myvar += '<tr>'+
'<td>'+arrObj[i].firstName+'</td>'+
'<td>'+arrObj[i].lastName+'</tD>'+
'<td>'+arrObj[i].age+'</th>'+
'</tr>'
}
myvar += '</table>';
console.log(myvar);
document.getElementById('myTable').innerHTML = myvar;
Hope this works

For loop with array doesn't work with innerHTML

I have a div with the ID="ranking" and I'd like to put there some info of a JavaScript array with a table where every row has tow columns: one for dados[i][25] and other for dados[i][26].
My code is this:
function dadosRanking(dados){
document.getElementById("ranking").innerHTML += '<table class="table"><tr><td valign="middle" class="question" colspan=2><h1>RANKING (+ PONTOS)</h1></td></tr><tr><td>PONTOS</td><td>UTILIZADOR</td></tr>'
for(var i=1;i<6;i++)
{
document.getElementById("ranking").innerHTML += '<tr><td>' + dados[i][25] + '</td><td>' + dados[i][26] + '</td></tr>';
}
document.getElementById("ranking").innerHTML += '</table>';
}
The code I expect was this:
<table class="table">
<tr>
<td valign="middle" class="question" colspan=2>
<h1>RANKING (+ PONTOS)</h1>
</td>
</tr>
<tr>
<td>PONTOS</td>
<td>UTILIZADOR</td>
</tr>
<tr>
<td>
100
</td>
<td>
Username
</td>
</tr>
</table>
However, the HTML code script write is this:
<table class="table">
<tr>
<td valign="middle" class="question" colspan=2>
<h1>RANKING (+ PONTOS)</h1>
</td>
</tr>
<tr>
<td>PONTOS</td>
<td>UTILIZADOR</td>
</tr>
</table>
"100Username"
Everytime you update innerHTML the browser will parse it and render it, to do that it will also try to 'fix' your HTML. This can have unintended consequences. Instead of pushing to innerHTML with a partial table definition, collect the HTML in a separate value and push to innerHTML once.
function dadosRanking(dados){
var s = "";
s += '<table class="table"><tr><td valign="middle" class="question" colspan=2><h1>RANKING (+ PONTOS)</h1></td></tr><tr><td>PONTOS</td><td>UTILIZADOR</td></tr>'
for(var i=1;i<6;i++) {
s += '<tr><td>' + dados[i][25] + '</td><td>' + dados[i][26] + '</td></tr>';
}
s += '</table>';
document.getElementById("ranking").innerHTML += s;
}
After
document.getElementById("ranking").innerHTML += '<table class="table"><tr><td valign="middle" class="question" colspan=2><h1>RANKING (+ PONTOS)</h1></td></tr><tr><td>PONTOS</td><td>UTILIZADOR</td></tr>'
innerHTML becomes:
<table class="table">
<tr><td valign="middle" class="question" colspan=2><h1>RANKING (+ PONTOS)</h1></td></tr>
<tr><td>PONTOS</td><td>UTILIZADOR</td></tr>
</table>
Note that the table has been closed!
After
document.getElementById("ranking").innerHTML += '<tr><td>foo</td><td>bar</td></tr>';
innerHTML becomes
<table>..</table>
foobar
<tr> and <td> are not valid outside of a table context so they're removed.
After
document.getElementById("ranking").innerHTML += '</table>';
innerHTML doesn't change because </table> doesn't do anything, there is no table to close.

Categories