HTML/Javascript - Tables - javascript

Good day,
I want a straightforward way to loop through data and display it in a table.
If there's more data then it must create more rows etc.
Columns are fixed.. for now.
Example the code looks like the following
<table>
<thead>
<tr>
<th>Client Name</th>
<th>Client Representative</th>
<th>Client Representative Position</th>
<th>Client Representative Email</th>
<th>Date Created</th>
</tr>
</thead>
<tbody>
<tr>
<td id="client_name"></td>
<td id="client_representative"> </td>
<td id="client_representative_position"> </td>
<td id="client_representative_email"></td>
<td id="date_created"></td>
</tr>
</tbody>
</table>
<script>
var data = {
client_name: "Example Company",
client_representative: "John",
client_representative_position: "Engineer",
client_representative_email: "John#example.com",
date_created: "25/02/2021",
} **
document.getElementById("client_name").innerHTML = data.client_name;
document.getElementById("client_representative").innerHTML = data.client_representative;
document.getElementById("client_representative_position").innerHTML = data.client_representative_position;
document.getElementById("client_representative_email").innerHTML = data.client_representative_email;
document.getElementById("date_created").innerHTML = data.date_created; **
</script>
Basically, I want to avoid that piece surrounded by ** (javascript) bit by having it loop through the data.
Thanks in advance!

You Can use jQuery append()
Try this
<html>
<head>
<script
src="https://code.jquery.com/jquery-3.5.1.min.js"
integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0="
crossorigin="anonymous"></script>
</head>
<body>
<table >
<thead >
<tr>
<th>Client Name</th>
<th>Client Representative</th>
<th>Client Representative Position</th>
<th>Client Representative Email</th>
<th>Date Created</th>
</tr>
</thead>
<tbody id="table-body">
</tbody>
</table>
</body>
<script>
var data = [ {
client_name : "Example Company",
client_representative:"John",
client_representative_position:"Engineer",
client_representative_email:"John#example.com",
date_created:"25/02/2021",
},
{
client_name : "Example Company 2",
client_representative:"John 2",
client_representative_position:"Engineer 2",
client_representative_email:"John2#example.com",
date_created:"5/02/2021",
},
]
for (let index = 0; index < data.length; index++) {
var html = "<tr>";
html +="<td>"+data[index].client_name+"</td>";
html +="<td>"+data[index].client_representative+"</td>";
html +="<td>"+data[index].client_representative_position+"</td>";
html +="<td>"+data[index].client_representative_email+"</td>";
html +="<td>"+data[index].date_created+"</td>";
html += "</tr>";
$('#table-body').append(html);
}
</script>
</html>

To get the names of the keys in an object, you can use the in keyword.
This just loops through the keys as strings, allowing you to use in to set the elements in the table.
for (key in data)
document.getElementById(key).innerHTML = data[key]

Related

Howto use Boostrap table to get column sum using external json file

I have the following bootstrap based table and I am trying to calculate the total MarketValue. Its reading an external json file. but for some reason its not adding the values.
the problem starts when i load an external json. file. How can i fix this?
$.getJSON("json/prep.json", function (jsonFromFile) {
$('#table1').bootstrapTable({
data: jsonFromFile.rows
})
var total1 = data.reduce(function(a, b){
return a + parseFloat(b.LongMarketValue);
}, 0);
document.querySelector('.total1').innerHTML = total1;
});
JSON - prep.json
{
"Name": "Julie Brown",
"Account": "C0010",
"LoanApproved": "12/5/2015",
"LastActivity": "4/1/2016",
"PledgedPortfolio": "1000",
"MaxApprovedLoanAmt": "10000",
"LoanBalance": "1849000",
"AvailableCredit": "2877.824375",
"Aging": "3",
"Brokerage": "My Broker",
"Contact": "oJohnson",
"ContactPhone": "-3614",
"RiskCategory": "Yellow",
"rows": [{
"Account": "086-1234",
"ClientName": "S Smth",
"AccountType": "tail",
"LongMarketValue": "$40000"
}, {
"Account": "086-1235",
"ClientName": "all Sth",
"AccountType": "REV Trust",
"LongMarketValue": "$55000"
},
{
"Account": "086-1236",
"ClientName": "Sly Smith",
"AccountType": "Reail",
"LongMarketValue": "$5500"
}]
}
HTML
<table id="table1">
<thead>
<tr>
<th data-field="state" data-checkbox="true"></th>
<th data-field="Account">Account #</th>
<th data-field="ClientName">Client</th>
<th data-field="AccountType">Account Type</th>
<th data-field="MarketValue"> Market Value</th>
</tr>
</thead>
<tfoot>
<tr>
<td></td>
<td></td>
<th></th>
<th> Total <span class="total1"></span></th>
</tr>
</tfoot>
</table>
data is undefined in your code, you have to retrieve data from table or from Json. Also your data returns a string with $ sign, so you have to remove it before parsing it.
Here is a working example.
// Code goes here
$(function () {
$.getJSON("https://api.myjson.com/bins/89vsf", function (jsonFromFile) {
$('#table1').bootstrapTable({
data: jsonFromFile.rows
})
var data = $('#table1').bootstrapTable('getData');
var total1 = data.reduce(function(a, b){
return a + parseFloat(b.LongMarketValue.replace('$',''));
}, 0);
document.querySelector('.total1').innerHTML = total1;
});
});
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<table id="table1">
<thead>
<tr>
<th data-field="state" data-checkbox="true"></th>
<th data-field="Account">Account #</th>
<th data-field="ClientName">Client</th>
<th data-field="AccountType">Account Type</th>
<th data-field="LongMarketValue"> Market Value</th>
</tr>
</thead>
<tfoot>
<tr>
<td></td>
<td></td>
<td></td>
<th></th>
<th> Total <span class="total1"></span></th>
</tr>
</tfoot>
</table>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script src="https://rawgit.com/wenzhixin/bootstrap-table/master/src/bootstrap-table.js"></script>
<script src="script.js"></script>
</body>
</html>
Here is a working plunker of the code. http://plnkr.co/edit/PSCR5iS7DSWkuQb1jv5P?p=preview
Hope this helps.

JavaScript function to populate table not working

I have an html table and I'm trying to create n number of rows using pure JavaScript, and populate the table using JSON data (I've created a variable with JSON data in it within the JavaScript code). The problem is, nothing happens when I click the button; the rows don't get created. For testing purposes, I tried adding a <p> element and some JavaScript to alter that element like this:
document.getElementById("test").innerHTML="TEST";
And that works so I know that there's something wrong with the code that inserts rows and the data.
Here is my code:
function populate() {
var rows = [{
"ID": "John",
"LastName": "Test",
"DOB": "03-12-1959",
"Gender": "M"
},
{
"ID": "John",
"LastName": "Test",
"DOB": "03-12-1959",
"Gender": "M"
}
];
var colNum = rows[0].length;
var testtable = document.getElementsByClassName("test-table");
for (var i = 0; i <= rows.length; i++) {
var testrow = testtable.insertRow();
for (var j = 0; j <= colNum; j++) {
var testcells = testrow.insertCell();
testcells.innerHTML = rows[i][j];
}
}
}
<button onclick="populate()">Test</button>
<table class="test-table">
<thead>
<tr>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>DOB</th>
<th>Gender</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<label for="row1"></label>123</td>
<td>John</td>
<td>Doe</td>
<td>02-15-1982</td>
<td>M</td>
</tr>
<tr>
<td colspan="6">
<input id="row1" type="checkbox">
<table>
<tr>
<th>Phone Number</th>
<td>555-3226</td>
<th>City:</th>
<td>New York</td>
</tr>
<tr>
<th>Hire Date:</th>
<td>8/13/12</td>
<th>Salary:</th>
<td>$48,000</td>
</tr>
</table>
</td>
</tr>
</tbody>
</table>
When I inspect element in the browser (firefox) it tells me that 'insertRow' is not a function.
Is there another way to do this? How can I fix this? Any help would be appreciated.
Here is the fiddle with the solution:
http://jsfiddle.net/7dfwrje7/4/
HTML
<button onclick="populate()">Test</button>
<table class="test-table">
<thead>
<tr>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>DOB</th>
<th>Gender</th>
</tr>
</thead>
<tbody id="data">
<tr>
<td><label for="row1"></label>123</td>
<td>John</td>
<td>Doe</td>
<td>02-15-1982</td>
<td>M</td>
</tr>
<tr>
<td colspan="6">
<input id="row1" type="checkbox">
<table>
<tr>
<th>Phone Number</th>
<td>555-3226</td>
<th>City:</th>
<td>New York</td>
</tr>
<tr>
<th>Hire Date:</th>
<td>8/13/12</td>
<th>Salary:</th>
<td>$48,000</td>
</tr>
</table>
</td>
</tr>
</tbody>
</table>
JS
function populate(){
var data = [
{
"ID" : "2",
"FirstName" : "John",
"LastName" : "Test",
"DOB": "03-12-1959",
"Gender":"M"
},
{
"ID" : "3",
"FirstName" : "Helen",
"LastName" : "Test",
"DOB": "03-12-1959",
"Gender":"M"
}
];
var tr, td;
var tbody = document.getElementById("data");
// loop through data source
for (var i = 0; i < data.length; i++) {
tr = tbody.insertRow(tbody.rows.length);
td = tr.insertCell(tr.cells.length);
td.setAttribute("align", "center");
td.innerHTML = data[i].ID;
td = tr.insertCell(tr.cells.length);
td.innerHTML = data[i].FirstName;
td = tr.insertCell(tr.cells.length);
td.innerHTML = data[i].LastName;
td = tr.insertCell(tr.cells.length);
td.innerHTML = data[i].DOB;
td = tr.insertCell(tr.cells.length);
td.innerHTML = data[i].Gender;
}
}
document.getElementsByClassName() returns a collection, not a single element. If you have multiple elements with the class, you need to loop over them; if there's just one, you need to index it:
var testtable = document.getElementsByClassName("test-table")[0];
The jfiddle seemed to not like the onclick on the HTML attribute.
You can put it in the JS instead, if necessary:
document.getElementById('myButt').onclick = populate;
For your rows JSON object, you are treating it like an array when you should be treating it like a map. You can get the keys of an object then iterate through the keys:
var colNum = Object.keys(rows[0]).length;
var testtable = document.getElementsByClassName("test-table")[0];
for(var i=0; i <= rows.length; i++){
var testrow = testtable.insertRow();
Object.keys(rows[i]).forEach(function (key) {
var testcells = testrow.insertCell();
testcells.innerHTML = rows[i][key];
});
}
}
I also made the same change as the pre-existing answer, for the call to getElementsByClassName().

jQuery load template inside a loop

I have a json file with some data and I am using a Js loop to load a jQuery template to iterate through and load a table made of 4 rows based on the data, so far I only get the last row. https://github.com/codepb/jquery-template
<script type="text/html" id="tableContent">
<tr>
<th>Key</th>
<th>Product</th>
<th>Bookings</th>
<th>%</th>
<th>Transactions</th>
</tr>
<tr>
<td data-content="">sth</td>
<td data-content="Product"></td>
<td data-content="Bookings"></td>
<td data-content="Percentage"></td>
<td data-content="Transactions"></td>
</tr>
</script>
function builTable(){
var table = "",
colors = ['col1', 'col2', 'col3', 'col4', 'col5', 'col6'];
for(i = 0; i< source.Products.length; i++){
$("table").loadTemplate($("#tableContent"),
{
Product: source.Products[i].Product,
Bookings: source.Products[i].Bookings,
Percentage: source.Products[i].Percentage,
Transaction: source.Products[i].Transaction
} );
$(document).ready(function(){
builTable();
});
<table border="1" cellpadding="2">
</table>
Is there something wrong inside the loop?
http://jsfiddle.net/9JV7t/1/
I think you just need to add an array because it loads the whole content just once and then overrides it again. But therefore you need to only include the data rows in the template and add the headings to the table (DEMO):
<script type="text/html" id="tableContent">
<tr>
<td data-content="">sth</td>
<td data-content="Product"></td>
<td data-content="Bookings"></td>
<td data-content="Percentage"></td>
<td data-content="Transactions"></td>
</tr>
</script>
Your table:
<table>
<thead>
<tr>
<th>Key</th>
<th>Product</th>
<th>Bookings</th>
<th>%</th>
<th>Transactions</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
And the js:
function builTable(){
$("tbody").loadTemplate($("#tableContent"), source.Products);
}

Create table using Mushtache.js

I am facing a problem while creating a table using Mushtache.js
View file:
<table class="table table-bordered table-hover table-striped tablesorter">
<thead>
<tr>
<th class="header">Name</th>
<th class="header">Email ID</th>
<th class="header">Contact Number</th>
<th class="header">Edit</th>
</tr>
</thead>
<tbody>
<div id="eTableList"></div>
<script id="eList" type="text/template">
<tr>
<td>{{name}}</td>
<td>{{email}}</td>
<td>{{contact_number}}</td>
<td>View/Edit</td>
</tr>
</script>
</tbody>
</table>
JS code:
function createTable(jsonEData){
var template = $("#eList").html();
expList = Mustache.render(template, jsonEData);
$("#expertTableList").html(expList);
}
I am calling this method as
<script language="javascript">
$(document).ready(function(){
createTable(<?php echo $this->eList;?>);
})
</script>
and the value of $this->eList = jsonEData is
[
{
"id": "52d3d523bdde226f17a581ba",
"name": "shgajsah",
"email": "0",
"contact_number": 2147483647
},
{
"id": "52d3d5c8bdde22c817a581ba",
"name": "fffsdf",
"email": "asa#ddjdj.com",
"contact_number": 323323232
}
]
I am not getting any error but table is not getting populated using above code. So please tell me where I am doing wrong?
You're not iterating over your items, give this a shot:
{{#.}}
<tr>
<td>{{name}}</td>
<td>{{email}}</td>
<td>{{contact_number}}</td>
<td>View/Edit</td>
</tr>
{{/.}}
or perhaps:
{{#each .}}
<tr> ... </tr>
{{/each .}}

How to get the data from API and put into tha table (Jquery)

Trying to store all the information that getting from JSONP in the table.
Have done the test with 'alert' to make sure that there are more info that only one line and can see that there are more info that one.
But when run it, in the table I can see title row and first row.
Can somebody correct my error?
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js">
</script>
<script>
jQuery(document).ready(function($) {
$.ajax({
url : "http://api.example.com/v1/deal/hotel?apikey=xxx&format=JSONP",
dataType : "jsonp",
success : function(parsed_json) {
$.each(parsed_json.Result, function( index, value ) {
alert( index + ": " + value.StarRating + " , "+ value.Url);
});
var from = parsed_json['Result'][0]['StartDate'];
document.getElementById("from").innerHTML = from;
var from = parsed_json['Result'][0]['StartDate'];
document.getElementById("from").innerHTML = from;
var to = parsed_json['Result'][0]['EndDate'];
document.getElementById("to").innerHTML = to;
var nights = parsed_json['Result'][0]['NightDuration'];
document.getElementById("nights").innerHTML = nights;
var currency = parsed_json['Result'][0]['CurrencyCode'];
document.getElementById("currency").innerHTML = currency;
var price = parsed_json['Result'][0]['Price'];
document.getElementById("price").innerHTML = price;
var link = parsed_json['Result'][0]['Url'];
document.getElementById("link").innerHTML = link;
//how to represent enlaces
var city = parsed_json['Result'][0]['City'];
document.getElementById("city").innerHTML = city;
var country = parsed_json['Result'][0]['CountryCode'];
document.getElementById("country").innerHTML = country;
var stars = parsed_json['Result'][0]['StarRating'];
document.getElementById("stars").innerHTML = stars;
}
});
});
</script>
</head>
<body>
<table id="t">
<tr>
<th>Start date</th>
<th>End date</th>
<th>Nights</th>
<th>Currency</th>
<th>Price</th>
<th>Link</th>
<th>City</th>
<th>Country Code</th>
<th>Star Rating</th>
</tr>
<tr>
<td id="from"></td>
<td id="to"></td>
<td id="nights"></td>
<td id="currency"></td>
<td id="price"></td>
<td id="link"></td>
<td id="city"></td>
<td id="country"></td>
<td id="stars"></td>
</tr>
</table>
</body>
</html>
The result of the Ajax callback is:
callback({"Errors":[],"Result":[{"FoundDate":"2013-12-04T16:11:36-08:00","CurrencyCode":"USD","NightDuration":"2.0","EndDate":"12/08/2013","Headline":"Cairo 5 Star Hotel, $36/night","IsWeekendStay":"true","Price":"36.0","StartDate":"12/06/2013","Url":"http‍://www.example.com/hotel/...&startDate=12/06/2013&endDate=12/08/2013&bid=0&sid=0","City":"Cairo","CountryCode":"EG","NeighborhoodLatitude":"30.0152","NeighborhoodLongitude":"31.1756","Neighborhood":"Cairo West - Giza","StarRating":"5.0","StateCode":"EG"},{"FoundDate":"2013-12-04T14:51:44-08:00",
If you have more than one line in result, then you have to -
Loop through it in the callback. You are not looping through it now. You are looping only for alert.
Dynamically create a new row in table for each line. You can clone the exiting tr for this using jquery clone method. But replace the id with 'class`.
Add data to that row pertaining to the line by modifying innerHtml of each td in the newly created row.
Finally, Append the row to the table
HTML -
<table id="t">
<tr>
<th>Start date</th>
<th>End date</th>
<th>Nights</th>
<th>Currency</th>
<th>Price</th>
<th>Link</th>
<th>City</th>
<th>Country Code</th>
<th>Star Rating</th>
</tr>
<tr class="first">
<td class="from"></td>
<td class="to"></td>
<td class="nights"></td>
<td class="currency"></td>
<td class="price"></td>
<td class="link"></td>
<td class="city"></td>
<td class="country"></td>
<td class="stars"></td>
</tr>
</table>
Javascript -
success : function(parsed_json) {
$.each(parsed_json.Result, function( index, record ) {
$row = $('.first').clone();
var from = record['StartDate'];
$row.find('.from').html(from);
//Similarly repeat the above two lines for other columns
//...
$('#t').append($row);
});
}

Categories