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.
Related
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);
});
});
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.
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>
So as a beginner, I have no idea how to create a table using Javascript. I can make a table using a simple html file but not in Javascript.
The output should have 2 columns and 4 rows. I also need to use the prompt tag in order to insert data for the second column. Not to mention that I need to average the total number in the 2nd column.
I tried searching but I got mixed results and its confusing me.so please help me
this is the html file
<html>
<body>
<table border="1" style="width:30%">
<tr>
<td>Rose</td>
<td>40</td>
</tr>
<tr>
<td>Daisy</td>
<td>50</td>
</tr>
<tr>
<td>Orchids</td>
<td>60</td>
</tr>
<tr>
<td>Flowers</td>
<td>150</td>
</tr>
</table>
</body>
</html>
Try this - >
var Rose = prompt("Enter price for Rose?");
var Daisy = prompt("Enter price for Daisy?");
var Orchids = prompt("Enter price for Orchids?");
var flowers = Number(Rose) + Number(Daisy) + Number(Orchids);
var table = document.createElement("table");
createTable();
function createTable(){
createTrTds("Rose",Rose);
createTrTds("Daisy",Daisy);
createTrTds("Orchids",Orchids);
createTrTds("Total",flowers);
document.getElementById("table").appendChild(table);
}
function createTrTds(text,value){
var tr = document.createElement("tr");
var td1 = document.createElement("td");
var td2 = document.createElement("td");
var txt1 = document.createTextNode(text);
var txt2 = document.createTextNode(value);
td1.appendChild(txt1);
td2.appendChild(txt2);
tr.appendChild(td1);
tr.appendChild(td2);
table.appendChild(tr);
}
td
{
border: 1px solid black;
}
<div id="table">
</div>
You will be helped by using a framework for this, jquery or angularjs comes to mind to solve it. However the pure JavaScript way looks like this:
This will create a table with inputs for the number of flowers and sum them up at the bottom when numbers change, you can also add more flower types in the JavaScript file.
var tabledef = [];
tabledef['Rose'] = 40;
tabledef['Daisy'] = 50;
tabledef['Orchids'] = 60;
writeTable();
function writeTable() {
var table = '<table border="1" style="width:30%">';
var sum = 0;
for (var i in tabledef) {
sum = sum + tabledef[i];
table = table + '<tr><td>' + i + '</td><td><input id="' + i + '" onchange="recalculate(this)" type="number" value="' + tabledef[i] + '"></td></tr>';
}
table = table + '<tr><td>Flowers</td><td>' + sum + '</td></tr></table>';
document.getElementById('myTable').innerHTML = table;
}
function recalculate(box) {
tabledef[box.id] = box.valueAsNumber;
writeTable();
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div id="myTable"></div>
<script src="createTable.js"></script>
</body>
</html>
You just need array with data and then fill table as thought it was an html document
var table = '<table border="1">',
data = [['Rose','Daisy','Orchids','Flowers'],[40,50,60,150]];
for (var i = 0; i < data[0].length; i++) {
table += '<tr>';
for (var j = 0; j < data.length; j++) {
table += '<td>' + data[j][i] + '</td>';
}
table += '</tr>';
}
table += '</table>';
document.getElementById('container').innerHTML = table;
http://jsfiddle.net/5pdac6sb/
I've created dynamic table using HTML and javascript but rather than applying alternate color, I want to apply distinct color to each row. How can I do so?
<!DOCTYPE HTML>
<html>
<head>
<title>Dynamic Page</title>
</head>
<body>
<table>
<tr>
<td>Enter Rows</td>
<td><input type="number" id="txtRows"/></td>
</tr>
<tr>
<td>Enter Columns</td>
<td><input type="number" id="txtCols"/></td>
</tr>
<tr>
<td colspan="2"><input type="button" id="btnDisplay" value="Display" onClick="createTable();"/></td>
</tr>
</table>
<table id="tbl_DynamicTable" border="1">
</table>
</body>
<script type="text/javascript">
function createTable()
{
debugger;
var rows = document.getElementById("txtRows").value;
var cols = document.getElementById("txtCols").value;
var table = document.getElementById("tbl_DynamicTable");
var str="";
for(var i=0;i<rows;i++)
{
str += "<tr id=row" + i +">";
//r = document.getElementById('tbl_DynamicTable').getElementsByTagName('<tr>');
//r.bgColor = colours[(i%k)/group | 0];
//mycurrent_row.style.backgroundColor = "#EEF4EA";
//mycurrent_row.style.backgroundColor =colours[(i%k)/group | 0];
for(var j=0;j<cols;j++)
{
if(i==0)
{
str += "<th> Header " + j + "</th>";
}
else
{
str += "<td> Row " + i + ", Cell "+ j + "</td>";
}
}
str += "</tr>";
}
table.innerHTML = str;
}
$("tr").style("bgcolor","red");
</script>
</html>
I don't know how to use jQuery with HTML page. I'm new to this. So if possible please let me know what is needed to include in this too.
You have many way to create a random color.
Use these example :
JAVASCRIPT
'#'+Math.floor(Math.random()*16777215).toString(16);
jQuery
(function(m,s,c){return (c ? arguments.callee(m,s,c-1) : '#') +
s[m.floor(m.random() * s.length)]})(Math,'0123456789ABCDEF',5)
And add this hexa random color on your TR when you generate it
HTML
<table border="1">
<tr bgcolor="#FF0000">
^ Here
<th>Month</th>
<th>Savings</th>
</tr>
<tr>
<td>January</td>
<td>$100</td>
</tr>
</table>
Other example on http://www.paulirish.com/2009/random-hex-color-code-snippets/
javascript approach (i suggest including jQuery):
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
function get_random_color() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.round(Math.random() * 15)];
}
return color;
}
// paint rows on document ready
$(function(){
paint_rows();
});
function paint_rows() {
$('#table_id tr').each(function(){
$(this).css('color', get_random_color());
});
}
</script>
just make sure to add enough color values into the array colors (can use hex values as well).
and, you can call the function paint_rows() whenever needed of course.
hope that helps.