I am trying to convert the Array to an HTML Table using jQuery. However, the browser shows nothing from the JSON file. Please see my codes below.
JSON file
[
{
"Book ID": "1",
"Book Name": "Computer Architecture",
"Category": "Computers",
"Price": "125.60"
},
{
"Book ID": "2",
"Book Name": "Asp.Net 4 Blue Book",
"Category": "Programming",
"Price": "56.00"
},
{
"Book ID": "3",
"Book Name": "Popular Science",
"Category": "Science",
"Price": "210.40"
}
]
HTML and JS
<script>
$(document).ready(function () {
$.getJSON("result.json", function (data) {
var arrItems = []; // THE ARRAY TO STORE JSON ITEMS.
$.each(data, function (index, value) {
arrItems.push(value); // PUSH THE VALUES INSIDE THE ARRAY.
});
// EXTRACT VALUE FOR TABLE HEADER.
var col = [];
for (var i = 0; i < arrItems.length; i++) {
for (var key in arrItems[i]) {
if (col.indexOf(key) === -1) {
col.push(key);
}
}
}
// CREATE DYNAMIC TABLE.
var table = document.createElement("table");
// CREATE HTML TABLE HEADER ROW USING THE EXTRACTED HEADERS ABOVE.
var tr = table.insertRow(-1); // TABLE ROW.
for (var i = 0; i < col.length; i++) {
var th = document.createElement("th"); // TABLE HEADER.
th.innerHTML = col[i];
tr.appendChild(th);
}
// ADD JSON DATA TO THE TABLE AS ROWS.
for (var i = 0; i < arrItems.length; i++) {
tr = table.insertRow(-1);
for (var j = 0; j < col.length; j++) {
var tabCell = tr.insertCell(-1);
tabCell.innerHTML = arrItems[i][col[j]];
}
}
// FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER.
var divContainer = document.getElementById("showData");
divContainer.innerHTML = "";
divContainer.appendChild(table);
});
});
Hi gusy, I am trying to convert the Array to an HTML Table using jQuery. However, the browser shows nothing from the JSON file. Please see my codes below.
Related
I have a dynamically generated table based on JSON response. The table has 3 columns - 1 for S. No., 2 for Name, and 3 is supposed to have two text links like Edit | Delete.
Edit and Delete are supposed to be clickable individually and upon clicking them I want to retrieve the respective JSON object to be able to process it further.
Example -
JSON response:
[
{
"id": 2,
"owner": 1,
"name": "General"
},
{
"id": 3,
"owner": 1,
"name": "Specific"
},
{
"id": 10,
"owner": 1,
"name": "One more"
},
{
"id": 11,
"owner": 1,
"name": "Test Category"
}
]
JS to generate table from the above JSON data:
function populateTable(data) {
const resLen = data.length;
var col = [];
col.push("S. No.");
for (var i=0; i<data.length; i++) {
for (var key in data[i]) {
if (col.indexOf(key) === -1 && key == "name") {
col.push(key);
}
}
}
col.push(" ");
var table = document.createElement("table");
var tr = table.insertRow(-1);
for (var i=0; i<col.length; i++) {
var th = document.createElement("th");
if (col[i] == "name") {
th.innerHTML = "Name";
tr.appendChild(th);
} else {
th.innerHTML = col[i];
tr.appendChild(th);
}
}
for (var i=data.length-1; i>=0; i--) {
tr = table.insertRow(-1);
for (var j=0; j<col.length; j++) {
var tabCell = tr.insertCell(-1);
if (j == 0) {
tabCell.innerHTML = ((data.length-1) - i)+1;
} else if (j == 2) {
tabCell.innerHTML = "Delete"
} else {
tabCell.innerHTML = data[i][col[j]];
}
}
}
var divContainer = document.getElementById("categoriesTable");
divContainer.innerHTML = "";
divContainer.appendChild(table);
}
Visual of the table:
I want to add clickable text in the third column (where currenlty Delete is) such that when I click on the text, I can retrieve its related JSON object and extract the id. I would like to do this in plain JS and HTML.
at first i suggest you using helper libraries like jquery(https://jquery.com) to have a better life but if you prefer pure javascript to attach event to dynamic created elements, your answer is event delegation which is answered in this post:
Attach event to dynamic elements in javascript
With jquery:
inside td tag, use button or link tag as delete button
add a css class(class="btn_delete") with a referal attribute to keep row id(data-rowid="25")
add jquery code
$(document).on('click','.btn_delete',function(){var rowid=$(this).data('rowid');//do something else ... });
You can use a html a tag:
text
I am trying to achieve something like this.
I am getting a json response after hitting a particular api command (a curl command let's say). I need to convert this result to an html. For this I am thinking of storing the result in an environment variable.
My intentions is to read this variable and so read the json data.
How can I read a environment variable in js?
I am using below program to map the json to html table.
<!DOCTYPE html>
<html>
<head>
<title>Convert JSON Data to HTML Table</title>
<style>
th, td, p, input {
font:14px Verdana;
}
table, th, td
{
border: solid 1px #DDD;
border-collapse: collapse;
padding: 2px 3px;
text-align: center;
}
th {
font-weight:bold;
}
</style>
</head>
<body>
<input type="button" onclick="CreateTableFromJSON()" value="Create Table From JSON" />
<p id="showData"></p>
</body>
<script>
function CreateTableFromJSON() {
var myBooks = [
{
"Book ID": "1",
"Book Name": "Computer Architecture",
"Category": "Computers",
"Price": "125.60"
},
{
"Book ID": "2",
"Book Name": "Asp.Net 4 Blue Book",
"Category": "Programming",
"Price": "56.00"
},
{
"Book ID": "3",
"Book Name": "Popular Science",
"Category": "Science",
"Price": "210.40"
}
]
// EXTRACT VALUE FOR HTML HEADER.
// ('Book ID', 'Book Name', 'Category' and 'Price')
var col = [];
for (var i = 0; i < myBooks.length; i++) {
for (var key in myBooks[i]) {
if (col.indexOf(key) === -1) {
col.push(key);
}
}
}
// CREATE DYNAMIC TABLE.
var table = document.createElement("table");
// CREATE HTML TABLE HEADER ROW USING THE EXTRACTED HEADERS ABOVE.
var tr = table.insertRow(-1); // TABLE ROW.
for (var i = 0; i < col.length; i++) {
var th = document.createElement("th"); // TABLE HEADER.
th.innerHTML = col[i];
tr.appendChild(th);
}
// ADD JSON DATA TO THE TABLE AS ROWS.
for (var i = 0; i < myBooks.length; i++) {
tr = table.insertRow(-1);
for (var j = 0; j < col.length; j++) {
var tabCell = tr.insertCell(-1);
tabCell.innerHTML = myBooks[i][col[j]];
}
}
// FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER.
var divContainer = document.getElementById("showData");
divContainer.innerHTML = "";
divContainer.appendChild(table);
}
</script>
</html>
As Quentin says: you can't, but look into Local Storage instead.
JavaScript, running client-side in an HTML document, has no access to environment variables at all. So you can't.
I need help on how to create table from data fetch from API server in html.
A possible duplicate of this question
I need to request json data from a url, then use that data to dynamically create table in html.
Below are my test.html
<!DOCTYPE html>
<html>
<head>
...
...
</head>
<body>
...
...
...
<div class="row">
<div class="col-xs-12">
<div class="box">
<div class="box-header">
<h3 class="box-title">Activity</h3>
</div>
<div id = "showData" class="box-body"></div>
</div>
</div>
</div>
<script src="../static/plugins/jQuery/jquery-2.2.3.min.js"></script>
<script src="../static/plugins/jQueryUI/jquery-ui.min.js"></script>
<script>
$.ajax({
url: "http://127.0.0.1:4220/pipeline/v1/bpwi/",
success: function (data) {
var col = [];
for (var i = 0; i < data.length; i++) {
for (var key in data[i]) {
if (col.indexOf(key) === -1) {
col.push(key);
}
}
}
var table = document.createElement("table");
var tr = table.insertRow(-1);
for (var i = 0; i < col.length; i++) {
var th = document.createElement("th");
th.innerHTML = col[i];
tr.appendChild(th);
}
for (var i = 0; i < data.length; i++) {
tr = table.insertRow(-1);
for (var j = 0; j < col.length; j++) {
var tabCell = tr.insertCell(-1);
tabCell.innerHTML = myBooks[i][col[j]];
}
}
var divContainer = document.getElementById("showData");
divContainer.innerHTML = "";
divContainer.appendChild(table);
}
})
</script>
</body>
</html>
Expected ajax response is something like this
[
{
"ID": "1",
"Name": "Computer",
"Category": "Computers",
"Price": "125.60"
},
{
"ID": "2",
"Name": "Blue",
"Category": "Sport",
"Price": "56.00"
},
{
"ID": "3",
"Book Name": "Science",
"Category": "Science",
"Price": "210.40"
}
]
I have refreshed my browser many times but the result is not good.
Here is the result
-----------------------------------------------------------------
Activity
-----------------------------------------------------------------
0
[
{
"
I
D
"
:
"
1
"
...
...
I am really new to javascript and some of good example I found is the possible question I posted above and here but both did not show a clear example on how to implement http request for getting the data from external source.
I really hope someone can pointed out for me what I did wrong in this code.
Thank you for your help and suggestion.
G'day,
So i've got this code to display a JSON file in a table and it works. What I want to know is how can I add a search bar for the table (I want to search by postcode)
function CreateTableFromJSON() {
var Data = [
{
"Service name": "3Bridges Community Incorporated",
"Physical Address Line 1": "1/72 Carwar Avenue",
"Physical Address Suburb": "CARSS PARK",
"Physical Address State": "NSW",
"Physical Address Post Code": 2221,
"Care Type": "Home Care Places",
"Residential Places": null,
"Home Care Low Places": 35,
"Home Care High Places": 10,
"Transition Care Places": null
}
]
// EXTRACT VALUE FOR HTML HEADER.
// ('Book ID', 'Book Name', 'Category' and 'Price')
var col = [];
for (var i = 0; i < Data.length; i++) {
for (var key in Data[i]) {
if (col.indexOf(key) === -1) {
col.push(key);
}
}
}
// CREATE DYNAMIC TABLE.
var table = document.createElement("table");
table.className += "alt";
// CREATE HTML TABLE HEADER ROW USING THE EXTRACTED HEADERS ABOVE.
var tr = table.insertRow(-1); // TABLE ROW.
for (var i = 0; i < col.length; i++) {
var th = document.createElement("th"); // TABLE HEADER.
th.innerHTML = col[i];
tr.appendChild(th);
}
// ADD JSON DATA TO THE TABLE AS ROWS.
for (var i = 0; i < Data.length; i++) {
tr = table.insertRow(-1);
for (var j = 0; j < col.length; j++) {
var tabCell = tr.insertCell(-1);
tabCell.innerHTML = Data[i][col[j]];
}
}
// FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER.
var divContainer = document.getElementById("showData");
divContainer.innerHTML = "";
divContainer.appendChild(table);
}
Some help would be greatly appreciated!
And here is my HTML:
<div class="table-wrapper">
<div id="showData"></div>
</div>
I'd say do a onchange event to a text input, and every time user defocus the text box, it will call your createTable function with a zip in parameter.
function search(zip)
{
CreateTableFromJSON(zip);
}
function CreateTableFromJSON(zip) {
var Data = [
{
"Service name": "3Bridges Community Incorporated",
"Physical Address Line 1": "1/72 Carwar Avenue",
"Physical Address Suburb": "CARSS PARK",
"Physical Address State": "NSW",
"Physical Address Post Code": 2221,
"Care Type": "Home Care Places",
"Residential Places": null,
"Home Care Low Places": 35,
"Home Care High Places": 10,
"Transition Care Places": null
}
]
//apply filter
Data=Data.filter(d=>d["Physical Address Post Code"]==zip || !zip)
// EXTRACT VALUE FOR HTML HEADER.
// ('Book ID', 'Book Name', 'Category' and 'Price')
var col = [];
for (var i = 0; i < Data.length; i++) {
for (var key in Data[i]) {
if (col.indexOf(key) === -1) {
col.push(key);
}
}
}
// CREATE DYNAMIC TABLE.
var table = document.createElement("table");
table.className += "alt";
// CREATE HTML TABLE HEADER ROW USING THE EXTRACTED HEADERS ABOVE.
var tr = table.insertRow(-1); // TABLE ROW.
for (var i = 0; i < col.length; i++) {
var th = document.createElement("th"); // TABLE HEADER.
th.innerHTML = col[i];
tr.appendChild(th);
}
// ADD JSON DATA TO THE TABLE AS ROWS.
for (var i = 0; i < Data.length; i++) {
tr = table.insertRow(-1);
for (var j = 0; j < col.length; j++) {
var tabCell = tr.insertCell(-1);
tabCell.innerHTML = Data[i][col[j]];
}
}
// FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER.
var divContainer = document.getElementById("showData");
divContainer.innerHTML = "";
divContainer.appendChild(table);
}
HTML .
<div class="table-wrapper">
<input type="text" name="searchText" value="" onchange="search(this.value)">
<div id="showData"></div>
</div>
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking us to recommend or find a tool, library or favorite off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.
Closed 8 years ago.
Improve this question
Is there any jQuery or javascript library that generates a dynamic table given json data?
I don't want to define the columns, the library should read the keys in the json hash and generate columns.
Of course, I can myself iterate through the json data and generate the html table. I just want to know if any such library exists which I can simply reuse.
Thanks all for your replies. I wrote one myself. Please note that this uses jQuery.
Code snippet:
var myList = [
{ "name": "abc", "age": 50 },
{ "age": "25", "hobby": "swimming" },
{ "name": "xyz", "hobby": "programming" }
];
// Builds the HTML Table out of myList.
function buildHtmlTable(selector) {
var columns = addAllColumnHeaders(myList, selector);
for (var i = 0; i < myList.length; i++) {
var row$ = $('<tr/>');
for (var colIndex = 0; colIndex < columns.length; colIndex++) {
var cellValue = myList[i][columns[colIndex]];
if (cellValue == null) cellValue = "";
row$.append($('<td/>').html(cellValue));
}
$(selector).append(row$);
}
}
// Adds a header row to the table and returns the set of columns.
// Need to do union of keys from all records as some records may not contain
// all records.
function addAllColumnHeaders(myList, selector) {
var columnSet = [];
var headerTr$ = $('<tr/>');
for (var i = 0; i < myList.length; i++) {
var rowHash = myList[i];
for (var key in rowHash) {
if ($.inArray(key, columnSet) == -1) {
columnSet.push(key);
headerTr$.append($('<th/>').html(key));
}
}
}
$(selector).append(headerTr$);
return columnSet;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body onLoad="buildHtmlTable('#excelDataTable')">
<table id="excelDataTable" border="1">
</table>
</body>
I have rewritten your code in vanilla-js, using DOM methods to prevent html injection.
Demo
var _table_ = document.createElement('table'),
_tr_ = document.createElement('tr'),
_th_ = document.createElement('th'),
_td_ = document.createElement('td');
// Builds the HTML Table out of myList json data from Ivy restful service.
function buildHtmlTable(arr) {
var table = _table_.cloneNode(false),
columns = addAllColumnHeaders(arr, table);
for (var i = 0, maxi = arr.length; i < maxi; ++i) {
var tr = _tr_.cloneNode(false);
for (var j = 0, maxj = columns.length; j < maxj; ++j) {
var td = _td_.cloneNode(false);
var cellValue = arr[i][columns[j]];
td.appendChild(document.createTextNode(arr[i][columns[j]] || ''));
tr.appendChild(td);
}
table.appendChild(tr);
}
return table;
}
// Adds a header row to the table and returns the set of columns.
// Need to do union of keys from all records as some records may not contain
// all records
function addAllColumnHeaders(arr, table) {
var columnSet = [],
tr = _tr_.cloneNode(false);
for (var i = 0, l = arr.length; i < l; i++) {
for (var key in arr[i]) {
if (arr[i].hasOwnProperty(key) && columnSet.indexOf(key) === -1) {
columnSet.push(key);
var th = _th_.cloneNode(false);
th.appendChild(document.createTextNode(key));
tr.appendChild(th);
}
}
}
table.appendChild(tr);
return columnSet;
}
document.body.appendChild(buildHtmlTable([{
"name": "abc",
"age": 50
},
{
"age": "25",
"hobby": "swimming"
},
{
"name": "xyz",
"hobby": "programming"
}
]));
You can use simple jQuery jPut plugin
http://plugins.jquery.com/jput/
<script>
$(document).ready(function(){
var json = [{"name": "name1","email":"email1#domain.com"},{"name": "name2","link":"email2#domain.com"}];
//while running this code the template will be appended in your div with json data
$("#tbody").jPut({
jsonData:json,
//ajax_url:"youfile.json", if you want to call from a json file
name:"tbody_template",
});
});
</script>
<table jput="t_template">
<tbody jput="tbody_template">
<tr>
<td>{{name}}</td>
<td>{{email}}</td>
</tr>
</tbody>
</table>
<table>
<tbody id="tbody">
</tbody>
</table>
Check out JSON2HTML http://json2html.com/ plugin for jQuery. It allows you to specify a transform that would convert your JSON object to HTML template. Use builder on http://json2html.com/ to get json transform object for any desired html template. In your case, it would be a table with row having following transform.
Example:
var transform = {"tag":"table", "children":[
{"tag":"tbody","children":[
{"tag":"tr","children":[
{"tag":"td","html":"${name}"},
{"tag":"td","html":"${age}"}
]}
]}
]};
var data = [
{'name':'Bob','age':40},
{'name':'Frank','age':15},
{'name':'Bill','age':65},
{'name':'Robert','age':24}
];
$('#target_div').html(json2html.transform(data,transform));