Populating local storage data to an HTML table? - javascript

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

Related

How to loop table HTML in javascript?

I have mockup like this
The HTML table to work with
The table above will calculate subtotal and total_harga using the entered value in jumlah. Calculations work fine, but my code is still using static JavaScript.
If there are a lot of rows in the table, it will be troublesome, if you have to write the getElementById code for all the inputs. How to use looping so that all the inputs can be handled without describing the table rows one by one. This is my HTML and JavaScript.
<div class="container">
<table class="tg" id="sales">
<thead>
<tr>
<th class="tg-0lax">No.</th>
<th class="tg-0lax">Item</th>
<th class="tg-0lax">Jumlah</th>
<th class="tg-0lax">Harga Satuan</th>
<th class="tg-0lax">Diskon Satuan</th>
<th class="tg-0lax">Sub-Total</th>
</tr>
</thead>
<tbody>
<tr>
<td class="tg-0lax">1</td>
<td class="tg-0lax">MIE INSTAN</td>
<td class="tg-keyup"> <input type="text" id="input1" name="fname" onkeyup="CalculationPrice()" placeholder="Masukan jumlah"><br></td>
<td class="tg-0lax" id="harga_satuan1">5000</td>
<td class="tg-0lax" id="diskon_satuan1">500</td>
<td class="tg-0lax" id="sub_total1"></td>
</tr>
<tr>
<td class="tg-0lax">2</td>
<td class="tg-0lax">SUSU UHT</td>
<td class="tg-keyup"><input type="text" id="input2" name="fname" onkeyup="CalculationPrice()" placeholder="Masukan jumlah"><br></td>
<td class="tg-0lax" id="harga_satuan2">6000</td>
<td class="tg-0lax" id="diskon_satuan2">1000</td>
<td class="tg-0lax" id="sub_total2"></td>
</tr>
<tr>
<td class="tg-0lax">3</td>
<td class="tg-0lax">KERIPIK</td>
<td class="tg-keyup"> <input type="text" id="input3" name="fname" onkeyup="CalculationPrice()" placeholder="Masukan jumlah"><br></td>
<td class="tg-0lax" id="harga_satuan3">8000</td>
<td class="tg-0lax" id="diskon_satuan3">500</td>
<td class="tg-0lax" id="sub_total3"></td>
</tr>
<tr>
<td class="tg-0lax"></td>
<td class="tg-1lax" colspan="4">TOTAL HARGA</td>
<td class="tg-0lax" id="total_price"></td>
</tr>
</tbody>
</table>
this is my code javascript :
function CalculationPrice() {
let input1 = document.getElementById("input1").value;
let input2 = document.getElementById("input2").value;
let input3 = document.getElementById("input3").value;
let hargaSatuan1 = document.getElementById("harga_satuan1").innerText;
let hargaSatuan2 = document.getElementById("harga_satuan2").innerText;
let hargaSatuan3 = document.getElementById("harga_satuan3").innerText;
let diskonSatuan1 = document.getElementById("diskon_satuan1").innerText;
let diskonSatuan2 = document.getElementById("diskon_satuan2").innerText;
let diskonSatuan3 = document.getElementById("diskon_satuan3").innerText;
if(input1.length == 0){
let total1 = document.getElementById("sub_total1").innerHTML = 0;
}else if(input1.length > 0){
let subinput = (parseInt(hargaSatuan1) - parseInt(diskonSatuan1)) * parseInt(input1)
let total1 = document.getElementById("sub_total1").innerHTML = subinput;
}
if(input2.length == 0){
let total2 = document.getElementById("sub_total2").innerHTML = 0;
}
else if(input2.length > 0){
let subinput2 = (parseInt(hargaSatuan2) - parseInt(diskonSatuan2)) * parseInt(input2)
let total2 = document.getElementById("sub_total2").innerHTML = subinput2;
}
if(input3.length == 0){
let total3 = document.getElementById("sub_total3").innerHTML = 0;
}
else if(input3 !== null){
let subinput3 = (parseInt(hargaSatuan3) - parseInt(diskonSatuan3)) * parseInt(input3)
let total3 = document.getElementById("sub_total3").innerHTML = subinput3;
}
let total1 = document.getElementById("sub_total1").innerText
let total2 = document.getElementById("sub_total2").innerText
let total3 = document.getElementById("sub_total3").innerText
let total_price = parseInt(total1) + parseInt(total2) + parseInt(total3)
let totalPriceHtml = document.getElementById("total_price").innerHTML = formatRupiah(total_price, "Rp.");
}
function formatRupiah(angka, prefix) {
let number_string = angka.toString().replace(/[^,\d]/g, ""),
split = number_string.split(","),
sisa = split[0].length % 3,
rupiah = split[0].substr(0, sisa),
ribuan = split[0].substr(sisa).match(/\d{3}/gi);
if (ribuan) {
separator = sisa ? "." : "";
rupiah += separator + ribuan.join(".");
}
rupiah = split[1] != undefined ? rupiah + "," + split[1] : rupiah;
return prefix == undefined ? rupiah : rupiah ? "Rp. " + rupiah : "";
}
Using ids on a table makes a lot of unnecessary work, it's much easier to rely on the structure of a static table. And, instead of inline event handlers, we can benefit from event delegation. Here's an example of how to listen input event on tbody and a simple reduce loop to calculate the total sum of subtotals.
const tbody = document.querySelector('#sales'),
rows = Array.from(tbody.rows), // All the rows of the tbody
total = rows.pop().cells[2]; // The TOTAL HARGA cell
function calcTot(e) {
const value = +e.target.value || 0,
rowIndex = e.target.closest('tr').rowIndex - 1, // Constant 1 = the amount of the rows in thead
cells = Array.from(rows[rowIndex].cells),
harga = +cells[3].textContent,
diskon = +cells[4].textContent,
sub = cells[5];
sub.textContent = harga - diskon * value;
total.textContent = rows.reduce((acc, row) => {
return acc += +row.cells[5].textContent;
}, 0);
}
// Calculate the first sums
rows.forEach(row => {
// Call calcTot with a fake event object
calcTot({target: row.cells[2]});
});
tbody.addEventListener('input', calcTot);
<div class="container">
<table class="tg">
<thead>
<tr>
<th class="tg-0lax">No.</th>
<th class="tg-0lax">Item</th>
<th class="tg-0lax">Jumlah</th>
<th class="tg-0lax">Harga Satuan</th>
<th class="tg-0lax">Diskon Satuan</th>
<th class="tg-0lax">Sub-Total</th>
</tr>
</thead>
<tbody id="sales">
<tr>
<td class="tg-0lax">1</td>
<td class="tg-0lax">MIE INSTAN</td>
<td class="tg-keyup"> <input type="text" name="fname[]" placeholder="Masukan jumlah"></td>
<td class="tg-0lax">5000</td>
<td class="tg-0lax">500</td>
<td class="tg-0lax"></td>
</tr>
<tr>
<td class="tg-0lax">2</td>
<td class="tg-0lax">SUSU UHT</td>
<td class="tg-keyup"><input type="text" name="fname[]" placeholder="Masukan jumlah"></td>
<td class="tg-0lax">6000</td>
<td class="tg-0lax">1000</td>
<td class="tg-0lax"></td>
</tr>
<tr>
<td class="tg-0lax">3</td>
<td class="tg-0lax">KERIPIK</td>
<td class="tg-keyup"> <input type="text" name="fname[]" placeholder="Masukan jumlah"></td>
<td class="tg-0lax">8000</td>
<td class="tg-0lax">500</td>
<td class="tg-0lax"></td>
</tr>
<tr>
<td class="tg-0lax"></td>
<td class="tg-1lax" colspan="4">TOTAL HARGA</td>
<td class="tg-0lax"></td>
</tr>
</tbody>
</table>
</div>
Notice also, that I've moved the sales id from the table tag to the tbody tag, and how the event handler function is used to calculate the subtotal and total sums without an actual event by passing an object which contains the needed information of the event object.
First, you should have the data source (in an array of objects). Such as:
var dataSource = [
{ id: 1, item: "MIE INSTAN", HargaSatuan: 5000, DiskonSatuan: 500 },
{ id: 2, item: "SUSU UHT", HargaSatuan: 6000, DiskonSatuan: 1000 },
{ id: 3, item: "KERIPIK", HargaSatuan: 8000, DiskonSatuan: 500 },
]
Then, you can loop through this array to construct your table, using either JQuery or JavaScript's "insertRow()".
Reference link for JavaScript's insertRow()
<html>
<head>
<style>
table {
border-collapse: collapse;
}
table, td, th {
border: 1px solid black
}
</style>
</head>
<body>
<table id="myTable">
<tr>
<th class="tg-0lax">No.</th>
<th class="tg-0lax">Item</th>
<th class="tg-0lax">Jumlah</th>
<th class="tg-0lax">Harga Satuan</th>
<th class="tg-0lax">Diskon Satuan</th>
<th class="tg-0lax">Sub-Total</th>
</tr>
</table>
<br>
<script>
function myFunction() {
var dataSource = [{
id: 1,
item: "MIE INSTAN",
hargaSatuan: 5000,
diskonSatuan: 500
},
{
id: 2,
item: "SUSU UHT",
hargaSatuan: 6000,
diskonSatuan: 1000
},
{
id: 3,
item: "KERIPIK",
hargaSatuan: 8000,
diskonSatuan: 500
},
]
var table = document.getElementById("myTable");
dataSource.forEach(function(data, index) {
var row = table.insertRow(index + 1);
var noCell = row.insertCell(0);
var itemCell = row.insertCell(1);
var jumlahCell = row.insertCell(2);
var hargaSatuanCell = row.insertCell(3);
var diskonSatuanCell = row.insertCell(4);
var subTotalCell = row.insertCell(5);
noCell.innerHTML = data.id;
itemCell.innerHTML = data.item;
hargaSatuanCell.innerHTML = data.hargaSatuan;
diskonSatuanCell.innerHTML = data.diskonSatuan
})
}
myFunction()
</script>
</body>
</html>
You only need to modify the datasource and refresh the table if there are any new data.
This might not be the best method of doing this, but this will give you a basic understanding on the algorithm and steps required for your needs.

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>

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

HTML table with editable fields accessed in javascript.

I am trying to build a table that will allow users to change the value of a cell(s) and then "submit" that data
to a JavaScript (only please) method that turns the tables data into a json dataset.
I started by trying to updated the value of just one field. QTY in this case. I am able to loop over the table and get the static values, but I am not able to catch the user input value.
question: What is a JavaScript only (if possible) way to capture user change(able) values from a table?
function updateQTY() {
//getData from table
//gets table
var lines = "";
var oTable = document.getElementById('items');
//gets rows of table
var rowLength = oTable.rows.length;
var line = "";
//loops through rows, skips firts row/header
for (i = 1; i < rowLength; i++) {
//gets cells of current row
var oCells = oTable.rows.item(i).cells;
var qty = oCells.item(2).innerHTML;
//alert("qty: " + wty);
qty = qty.substr(oCells.item(2).innerHTML.indexOf('value=') + 7);
qty = qty.substr(0, qty.indexOf('" class='));
//alert(qty);
line = line +
'{ "item": "' + oCells.item(0).innerHTML + '",' +
' "discription": "' + oCells.item(1).innerHTML + '",' +
' "qty": "' + qty + '"},'
}
//alert(line);
var jsonData = JSON.parse('[' + line + '{"quickwayto":"dealwith,leftbyloop"}]');
alert("lines: " + JSON.stringify(jsonData));
}
<form action='#'>
<table class='mdl-data-table mdl-js-data-table' id='items'>
<thead>
<tr>
<th>item</th>
<th>discription</th>
<th>QTY</th>
</tr>
</thead>
<tbody>
<tr>
<td class='mdl-data-table__cell--non-numeric'> widget_1 </td>
<td class='mdl-data-table__cell--non-numeric'>it's fun</td>
<td>
<div class='mdl-textfield mdl-js-textfield'><input type='text' name='qty1' id='value1' value='5' class='mdl-textfield__input'></div>
</td>
</tr>
<tr>
<td class='mdl-data-table__cell--non-numeric'> widget_2 </td>
<td class='mdl-data-table__cell--non-numeric'>it's super fun</td>
<td>
<div class='mdl-textfield mdl-js-textfield'><input type='text' name='qty2' id='value2' value='5' class='mdl-textfield__input'></div>
</td>
</tr>
</tbody>
</table>
<div>
<input type='button' value='update' onclick='updateQTY()' class='mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect'>
</div>
</form>
THANK YOU
Instead of selecting the entire td element, retrieve only what you really need using querySelector (or use jQuery if possible). Find the input element and access the value, it's a lot easier than doing all of that unecessary parsing of the inner html of the entire cell.
function updateQTY() {
//getData from table
//gets table
var lines = "";
var oTable = document.getElementById('items');
//gets rows of table
var rowLength = oTable.rows.length;
var line = "";
//loops through rows, skips firts row/header
for (i = 1; i < rowLength; i++) {
//gets cells of current row
var oCells = oTable.rows.item(i).cells;
var qty = oCells.item(2).querySelector(".mdl-textfield__input").value;
line = line +
'{ "item": "' + oCells.item(0).innerHTML + '",' +
' "discription": "' + oCells.item(1).innerHTML + '",' +
' "qty": "' + qty + '"},'
}
//alert(line);
var jsonData = JSON.parse('[' + line + '{"quickwayto":"dealwith,leftbyloop"}]');
alert("lines: " + JSON.stringify(jsonData));
}
<form action='#'>
<table class='mdl-data-table mdl-js-data-table' id='items'>
<thead>
<tr>
<th>item</th>
<th>discription</th>
<th>QTY</th>
</tr>
</thead>
<tbody>
<tr>
<td class='mdl-data-table__cell--non-numeric'> widget_1 </td>
<td class='mdl-data-table__cell--non-numeric'>it's fun</td>
<td>
<div class='mdl-textfield mdl-js-textfield'><input type='text' name='qty1' id='value1' value='5' class='mdl-textfield__input'></div>
</td>
</tr>
<tr>
<td class='mdl-data-table__cell--non-numeric'> widget_2 </td>
<td class='mdl-data-table__cell--non-numeric'>it's super fun</td>
<td>
<div class='mdl-textfield mdl-js-textfield'><input type='text' name='qty2' id='value2' value='5' class='mdl-textfield__input'></div>
</td>
</tr>
</tbody>
</table>
<div>
<input type='button' value='update' onclick='updateQTY()' class='mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect'>
</div>
</form>
You need to use document.getElementById('value2').value instead of .innerHTML.indexOf('value=')
You're making yourself a lot of work here. You have a table. All you need to do is convert that to JSON. I would suggest you look at the library below that does that in around one line of native java-script.
http://www.developerdan.com/table-to-json/

Dynamic table with bootstrap

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>';

Categories