How to add clickable text in dynamically created table in JS - javascript

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

Related

Convert Json into table or structured data [duplicate]

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

How to read an array/data from other html file in jQuery and create dynamic table (PLC webserver)

I`m working with PLC controllers. I have created a webserver on a PLC and I want to show data block in html. I already know that I must write:
:="webdata".counter[0]:
But I have 2 problems.
1) I want to load this data in table and here is a problem. When i try:
for(var r = 0; r < 3; r++) {
document.write(":=\"webdata\".test[" + r + "]:")
};
There is nothing in page (in PLC i have an array of 55). So I`ve created an array and table
var edr = [
{
"Pallet": ":="webdata".test[0]:",
"code": "8501H984P",
"Cycles": ":="pallet_data".cycles[0]:"
},
{
"Pallet": ":="webdata".test[1]:",
"code": "8501H984P",
"Cycles": ":="pallet_data".cycles[1]:"
}
]
var col = [];
for (var i = 0; i < edr.length; i++) {
for (var key in edr[i]) {
if (col.indexOf(key) === -1) {
col.push(key);
}
}
}
var table = document.createElement("table");
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);
}
for (var i = 0; i < edr.length; i++) {
tr = table.insertRow(-1);
for (var j = 0; j < col.length; j++) {
var tabCell = tr.insertCell(-1);
tabCell.innerHTML = edr[i][col[j] ];
}
}
var divContainer = document.getElementById("showData");
divContainer.innerHTML = "";
divContainer.appendChild(table);
And this works but I have to type whole array. Is there a solution of this?
2) Also to update data I use jQuery
$(document).ready(function(){
$.ajaxSetup({ cache: false });
setInterval(function() {
$.get("IO.html", function(result){
$('#counter').text(result.trim());
});
},3000);
});
but I have to create a html file with :="webdata".test[0]: inside. I cannot find a solution to extract only a part of html document.
I will be grateful for your help :)

How to make a search query for a JSON file in Javascript

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>

Trying to convert the JSON file to an HTML Table using jQuery

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.

Convert json data to a html table [closed]

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

Categories