Unable to show all data from database in the table - javascript

for(var i =0; i< keys.length;i++){
var k = keys[i];
resultUserName.innerHTML = `
<table class="responsive-table highlight">
<thead>
<tr>
<th>Issued Raised By</th>
<th>Issue For</th>
<th>Issue Logged Time</th>
<th>Issue Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>${userData[k].raisedBy}</td>
<td>${userData[k].issueFor}</td>
<td>${userData[k].issueLoggedDate}</td>
<td>${userData[k].issueDescription}</td>
</tr>
</tbody>
</table>
`;
}
I'm trying to retrieve all the data from the DB into a table, it's showing all the data when I console log it but when i display it on the page it is only showing the last entry made, can anyone point out what's wrong in the code above.

You need to build header elements separately outside loop and build each row data in loop as string, finally append to your DOM
var innerHtml = '<table class="responsive-table highlight">'+
'<thead>'+
'<tr>'+
'<th>Issued Raised By</th>'+
'<th>Issue For</th>'+
'<th>Issue Logged Time</th>'+
'<th>Issue Description</th>'+
'</tr>'+
'</thead>'+
'<tbody>';
for(var i =0; i< keys.length;i++){
var k = keys[i];
innerHTML += '<tr>'+
'<td>${userData[k].raisedBy}</td>'+
'<td>${userData[k].issueFor}</td>'+
'<td>${userData[k].issueLoggedDate}</td>'+
'<td>${userData[k].issueDescription}</td>'+
'</tr>';
}
resultUserName.innerHtml = innerHTML+"</tbody></table>";

var resultUserName = document.getElementById('resultUserName');
var tableHeader = '<table><thead><tr><th>Issued Raised By</th><th>Issue For</th><th>Issue Logged Time</th><th>Issue Description</th></tr></thead><tbody>;
var tableFooter = '</tbody></table>'
var tableBody = '';
for(var i =0; i< keys.length;i++){
var k = keys[i];
tableBody = tableBody + '<tr>'+
'<td>${userData[k].raisedBy}</td>'+
'<td>${userData[k].issueFor}</td>'+
'<td>${userData[k].issueLoggedDate}</td>'+
'<td>${userData[k].issueDescription}</td>'+
'</tr>';
}
resultUserName.innerHTML = tableHeader + tableBody + tableFooter;
This should solve your problem. In for loop inner html is getting replaced.

Related

Creating a table through local storage data?

How can I populate my table with an array of local storage data?
function savePlayer() {
let Player = {player,score};
localStorage.setItem("Player", JSON.stringify(Player));
let getPlayerScore = Player;
let text = document.getElementById("topScores");
for(let i = 0; i <Player.length; i++){
text += "<tr>";
text += "<td>" + getPlayerScore[i].player + "</td>";
text += "<td>" + getPlayerScore[i].score + "</td></tr>";
}
Here's the HTML:
<body>
<table id = "topScores">
<tr>
<th>Username</th>
<th>Score</th>
</tr>
</table>
</body>
What am I doing wrong?
The Player.toString() isn't what you think it is.
var player = "Mario";
var score = 1000;
var Player = {
player,
score
};
// Print Player
console.log(JSON.stringify(Player));
console.log(Player.toString());
You can't just add text to an element; you need to set it though
innerHTML. Sadly, however, you can't set it for each row, because the DOM will try to end the tr tag, so you need to set everything at the same time through a string.
I couldn't get localStorage to work in the snippet so I commented out the code without testing it.
Another solution would be to append the elements, and honestly, that's what I would prefer, but I didn't want to steer to far away from your original solution, and I didn't want fix the "feature" where the DOM is autocompleting tr tags.
function savePlayer() {
// This wasn't an array to begin with, so I fixed that.
let Player = [{"player": "player","score": 10}];
// It's usually preferred to refer to a public constant when accessing localStorage.
let localStorageKey = "player";
/* localStorage.setItem(localStorageKey, JSON.stringify(Player));
let getPlayerScore = JSON.parse(localStorage.getItem(localStorageKey));*/
let getPlayerScore = Player;
let text = document.getElementById("topScores");
var playerRow = "";
for(let i = 0; i < getPlayerScore.length; i++){
playerRow = "<tr>";
playerRow += "<td>" + getPlayerScore[i].player + "</td>";
playerRow += "<td>" + getPlayerScore[i].score + "</td></tr>";
}
text.innerHTML += playerRow;
}
<body onload="savePlayer()">
<table id="topScores">
<tr>
<th>Username</th>
<th>Score</th>
</tr>
</table>
</body>

jQuery sum the values of table rows

hello i have this table
i want to get the total of each row in the total column
jQuery
//Monthly Marketing Cost Report
$.get('/dashboard/costs', function(data){
$.each(data,function(i,value){
var leads = $('#leads');
var budget_total_year = $('#full_year_cost');
var budget_total_month = $('#share_cost');
var budget_per_lead = $('#cost_per_lead');
leads.append('<th>' + value.olxTotal + '</th>');
budget_total_year.append('<th>' + value.budget_total_year + '</th>');
budget_total_month.append('<th>' + value.budget_total_month + '</th>');
budget_per_lead.append('<th>' + value.budget_per_lead + '</th>');
})
})
HTML
<tbody id="tableData-marketMonth">
<tr id="leads">
<th>Leads</th>
</tr>
<tr id="full_year_cost">
<th>Full Year Cost</th>
</tr>
<tr id="share_cost">
<th>{{date('F')}} Share of Cost</th>
</tr>
<tr id="cost_per_lead">
<th>Cost per Lead</th>
</tr>
</tbody>
i was going to calculate the total through php but i though it can be easier
using jQuery just putting the sum of each row at the end
Thank you very much
Create variables before the loop. add to the variables in the loop and then assign the sum at the end.
$.get('/dashboard/costs', function(data){
var sumLeads = 0;
var sumFullYearCost = 0;
var sumShareCost = 0;
var sumCostPerLead = 0;
var tr_leads = $('#leads');
var tr_budget_total_year = $('#full_year_cost');
var tr_budget_total_month = $('#share_cost');
var tr_budget_per_lead = $('#cost_per_lead');
$.each(data,function(i,value){
tr_leads.append('<th>' + value.olxTotal + '</th>');
tr_budget_total_year.append('<th>' + value.budget_total_year + '</th>');
tr_budget_total_month.append('<th>' + value.budget_total_month + '</th>');
tr_budget_per_lead.append('<th>' + value.budget_per_lead + '</th>');
sumLeads += value.olxTotal;
sumFullYearCost += value.budget_total_year;
sumShareCost += value.budget_total_month;
sumCostPerLead += value.budget_per_lead;
});
tr_leads.append('<th>' + sumLeads + '</th>');
tr_budget_total_year.append('<th>' + sumFullYearCost + '</th>');
tr_budget_total_month.append('<th>' + sumShareCost + '</th>');
tr_budget_per_lead.append('<th>' + sumCostPerLead + '</th>');
});
Example for leads row using Array.map and Array.reduce. Use jQuery to get the td elements.
var leads = $('#leads');
const total = leads.children('td').toArray().map(x=>Number(x.innerHTML)).reduce((sum, x) => sum + x)
leads.append(`<th>${total}</th>`);
Try something like this.
$('#tableData-marketMonth tr').each(function () {
var row = $(this);
var rowTotal = 0;
$(this).find('th').each(function () {
var th = $(this);
if ($.isNumeric(th.text())) {
rowTotal += parseFloat(th.text());
}
});
row.find('th:last').text(rowTotal);
});
NOTE: change 'th' to 'td' if you have td's. Looking at your jquery, it looks like you are appending th's.
You can use my written code to vote if you like it...
HTML
<table>
<thead>
<tr>
<th>MAX ATK</th>
<th>MAX DEF</th>
<th>MAX HP</th>
<th>Overall</th>
</tr>
</thead>
<tbody>
<tr>
<td class="combat">8170</td>
<td class="combat">6504</td>
<td class="combat">6050</td>
<td class="total-combat"></td>
</tr>
<tr>
<td class="combat">8500</td>
<td class="combat">10200</td>
<td class="combat">7650</td>
<td class="total-combat"></td>
</tr>
<tr>
<td class="combat">9185</td>
<td class="combat">7515</td>
<td class="combat">9185</td>
<td class="total-combat"></td>
</tr>
</tbody>
</table>
jquery
$(document).ready(function () {
//iterate through each row in the table
$('tr').each(function () {
//the value of sum needs to be reset for each row, so it has to be set inside the row loop
var sum = 0
//find the combat elements in the current row and sum it
$(this).find('.combat').each(function () {
var combat = $(this).text();
if (!isNaN(combat) && combat.length !== 0) {
sum += parseFloat(combat);
}
});
//set the value of currents rows sum to the total-combat element in the current row
$('.total-combat', this).html(sum);
});
});

HTML table not showing table header

I have an html table with 3 columns and any number of rows (based on a database output.)
var fields = ['a','b','c']; //variable from database
var data = ['p', 'q', 'r']; //variable from database
var who = ['x', 'y', 'z']; //variable from database
$(function() {
var table = $("#resultTable");
var rowNum = 3;
var resultHtml = '';
for(var i = 0 ; i < rowNum ; i++) {
resultHtml += ["<tr>",
"<td>",
fields[i],
"</td>",
"<td>",
data[i],
"</td>",
"<td>",
who[i],
"</td>",
'</tr>'].join("\n");
}
table.html(resultHtml);
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="resultTable">
<tr>
<th>Question</th>
<th>Decision</th>
<th>Whose Decision</th>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table>
The table shows the content properly but doesn't show the headers of each of the column such as Question, Decision, Whose Decision
What am I missing?
You replaced whole html.
You need to apped html like
table.append(resultHtml);
By using table.html(...) you override the entire content of your table (include the header).
You can use something like that:
var fields = ['a','b','c']; //variable from database
var data = ['p', 'q', 'r']; //variable from database
var who = ['x', 'y', 'z']; //variable from database
$(function() {
var table = $("#resultTable");
var rowNum = 3;
var resultHtml = $('<table>').append(table.find('tr').first()).html();
for(var i = 0 ; i < rowNum ; i++) {
resultHtml += ["<tr>",
"<td>",
fields[i],
"</td>",
"<td>",
data[i],
"</td>",
"<td>",
who[i],
"</td>",
'</tr>'].join("\n");
}
table.html(resultHtml);
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="resultTable">
<tr>
<th>Question</th>
<th>Decision</th>
<th>Whose Decision</th>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table>
Because you use resultHtml to replace table HTML code.
You are overwriting the table in the javascript from what I can see. table.html(resultHtml) is replacing what you have in the html code.

Looping through HTML table with Javascript/jQuery

I am struggling to figure out how to loop through a table in HTML.
I have a 2D Javascript object that I would like to populate cells with index i,j from myObject[i][j]. I have a basic html table template but with blank <td></td> tags. I have looked at ways to do it in jQuery and Javascript, but to no avail.
Edit: Here's my code:
var table = document.getElementById("myTable");
for (var i = 0, row; row = table.rows[i]; i++) {
for (var j = 0, col; col = row.cells[j]; j++) {
col = myObject[i][j]
}
}
My HTML is just a standard table eg.:
<table id="myTable">
<thead>
<tr>
<th></th>
</tr>
<tr>
<td></td>
</tr>
</thead>
<tbody>
<tr>
<th></th>
<td></td>
</tbody>
</table>
Any help would be greatly appreciated.
Thanks #bulicmatko
You can try something like this: jsfiddle.net/pt9go1s6
You can try something like this:
HTML:
<div id="tableWrap"></div>
JS:
var tableWrap = document.getElementById("tableWrap");
var data = [
['First Name', 'Last Name', 'Age'],
['Johnny', 'Bravo', '27'],
['Bugs', 'Bunny', '35'],
['Mickey', 'Mouse', '35'],
];
var table = "<table>";
for (var i = 0; i < data.length; i++) {
table += "<tr>";
for (var j = 0; j < data[i].length; j++) {
table += "<td>" + data[i][j] + "<td>";
}
table += "</tr>";
}
table += "</table>";
tableWrap.innerHTML = table;
Here is the demo.
Hope it helps ;)
A jQuery solution could be use child related selectors to filter relevant cells.
var ar = [
['A', 'B'],
['C', 'D']
];
for (var r = 0; r < 2; ++r) {
for (var c = 0; c < 2; ++c) {
$('table tr:nth-of-type(' + (r + 1) + ') td:nth-of-type(' + (c + 1) + ')').text(ar[r][c]);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
<tr>
<td>.</td>
<td>.</td>
</tr>
<tr>
<td>.</td>
<td>.</td>
</tr>
</table>

Dynamically How to append more rows with columns into table using javascript

I want to append 3 rows into table with 3 column.I tried the following code,but it's not working.
html Code:
<table width="50%" border="0" cellspacing="2" cellpadding="5" class="height">
</table>
javascriptcode:
var table=document.getElementsByClassName('height') ;
//creating inputfield with attribute
var newField=document.createElement('input');
newField.setAttribute('type','text');
//creating <td>
var newTd=document.createElement('td');
//appending newField into td
newTd.appendChild(newField);
//creating <tr> element
var newTr=document.createElement('tr');
//appending 3 <td>(newTd) elements,but here 3 <td>'s are not appending
newTr.appendChild(newTd);
newTr.appendChild(newTd);
newTr.appendChild(newTd);
//the above code was not working,if it works I want to append 3 <tr> into <table>.
I don't want to use external libraries(jquery,....) .
thanks
Here is a suggestion:
var table = document.getElementsByClassName('height')[0]; //I added [0] here
for (var i = 0; i < 3; i++) {
var newField = document.createElement('input');
newField.setAttribute('type', 'text');
var newTd = document.createElement('td');
newTd.appendChild(newField);
var newTr = document.createElement('tr');
newTr.appendChild(newTd);
table.appendChild(newTr); //you had forgoten this one
}
Demo here
See http://coding.smashingmagazine.com/2013/10/06/inside-the-box-with-vanilla-javascript/ and goto to 'The API' section. This page explains about the default JS table DOM api.
It consists of the following methods:
insertRow()
deleteRow()
insertCell()
deleteCell()
createCaption()
deleteCaption()
createTHead()
deleteTHead()
Does this solution suits your needs?
table.innerHTML = new Array(4).join(
'<tr>' + new Array(4).join('<td><input type="text" /></td>') + '</tr>'
);
Another try:
var table = document.getElementsByTagName('table')[0];
// creates a template row with 3 cells
var tr = document.createElement('tr');
tr.innerHTML = new Array(4).join(
'<td><input type="text" /></td>'
);
// appends 3 rows to the table by cloning the template row
for (var i = 0; i < 3; i++) {
table.appendChild(tr.cloneNode(true));
}
<table width="50%" border="0" cellspacing="2" cellpadding="5" class="height"></table>

Categories

Resources