How to make HTML table from JSON objects data - javascript

I am trying to create an HTML table from JSON objects data with a for loop in a function. Below is the key part of my code that is clearly not working as intended and I am struggling to figure it out.
var table = ''
var forLoopData = function() {
for (j=0; j<dataJson.length; j++) {
table += '<tr';
for(var i=0; i<6; i++) {
table += "<td>" dataJson[i].id "</td>" "<td>"dataJson[i].firstName"</td>" "<td>"dataJson[i].lastName"</td>" "<td>"dataJson[i].dateOfBirth"</td>" "<td>"dataJson[i].function"</td>" "<td>"dataJson[i].experience"</td>";
}
table += </tr>
}
};
forLoopData();
document.write('<table>' + table + '</table>');

Your table lacks the table, tbody and tr tags.
<table>
<tbody>
<tr>
<td>dataJson[i].id</td>
<td>dataJson[i].firstName</td>
<td>dataJson[i].lastName</td>
</tr>
</tbody>
</table>
This is what you need to build.
Here is how:
var table = "<table><tbody>";
for(var i=0; i<6; i++) {
table += "<tr>" ;
table += "<td>" + dataJson[i].id "</td>" ;
table += "<td>" + dataJson[i].firstName + "</td>" ;
table += "<td>" + dataJson[i].lastName + "</td>" ;
table += "</tr>" ;
}
table += "</tbody></table>";
with your table ready you can use document.write(table)

Thank you everyone for trying to help me. Unfortunately I dropped this idea and did not have the chance to test your answers. Combining vanilla JavaScript with html elements is still hard for me and I decided to go with bootstrap framework. Below is code I used:
$.getJSON("data.json", function(data){
var items = [];
$.each(data, function(key, val){
items.push("<tr>");
items.push("<td id =''"+key+"''>"+val.id+"</td>");
items.push("<td id =''"+key+"''>"+val.firstName+"</td>");
items.push("<td id =''"+key+"''>"+val.lastName+"</td>");
items.push("<td id =''"+key+"''>"+val.dateOfBirth+"</td>");
items.push("<td id =''"+key+"''>"+val.function+"</td>");
items.push("<td id =''"+key+"''>"+val.experience+"</td>");
items.push("</tr>");
});
$("<tbody/>", {html: items.join("")}).appendTo("table");
});

Related

Append button to a table row dynamically using jquery

I have an array of JavaScript JSON objects which is being parsed from a JSON formatted-string. Now what I'm doing is that I'm looping through the array and append the data to a table within the page.
jQuery Code:
$.each(objArr, function(key, value) {
var tr = $("<tr />");
$.each(value, function(k, v) {
tr.append($("<td />", {
html: v
}));
$("#dataTable").append(tr);
})
})
The code works perfectly and the table is getting populated successfully
But what I'm looking for is that, I want to add a delete button at the end of the row, by which the user will delete the row, and it also important to handle the click event in order to perform the required action
I've done this in another way, but it is not that efficient, I want to use the code above to accomplish that as it is more efficient:
for (var i = 0; i < objArr.length; i++) {
var tr = "<tr>";
var td1 = "<td>" + objArr[i]["empID"] + "</td>";
var td2 = "<td>" + objArr[i]["fname"] + "</td>";
var td3 = "<td>" + objArr[i]["lname"] + "</td>";
var td4 = "<td>" + objArr[i]["phone"] + "</td>";
var td5 = "<td>" + objArr[i]["address"] + "</td>";
var td6 = "<td >" + objArr[i]["deptID"] + "</td>";
var td7 = "<td>" + objArr[i]["email"] + "</td>";
var td8 = "<td>" + '<button id="' + objArr[i]["empID"] + '" value="' + objArr[
i]["empID"] + '" onclick="onClickDelete(' + objArr[i]["empID"] +
')">Delete</button>' + "</td></tr>";
$("#dataTable").append(tr + td1 + td2 + td3 + td4 + td5 + td6 + td7 + td8);
}
Any suggestions please?
Try something like this:
$.each(objArr, function (key, value) {
var tr = $("<tr />");
$.each(value, function (k, v) {
tr.append($("<td />", { html: v }));
tr.append("<button class='remove' />");
$("#dataTable").append(tr);
})
})
This shall append the button at the end of the tr with class remove.
Try this, I've include event handler for the each buttons inside the table.
CHANGES:
Adding Event Listener for each buttons inside the table.
Call method (function) with parameters.
Note:
I am using, fadeOut method for fading purposes only. So you can see the changes. You can change the script as your need.
EXPLAINS :
var cRow = $(this).parents('tr'); on this line we have $(this) which mean we've select the button object that you've clicked, and search the parent with tag-name tr. We need to do this because we need to take control of all data inside the tr object.
var cId = $('td:nth-child(2)', cRow).text(); has mean search second td object wich located on cRow object. And take the text from the selected td.
JQUERY REFFERENCES :
.parents()
:nth-child()
$(this) OR $(this)
$(document).ready(function() {
var jsonData = [
{id: 'A01', name: 'Fadhly'},
{id: 'A02', name: 'Permata'},
{id: 'A03', name: 'Haura'},
{id: 'A04', name: 'Aira'}
];
$.each(jsonData, function(key, val) {
var tr = '<tr>';
tr += '<td>' + (key + 1) + '</td>';
tr += '<td>' + val.id + '</td>';
tr += '<td>' + val.name + '</td>';
tr += '<td><button class="delete" data-key="'+ (key + 1) +'">Delete</button></td>';
tr += '</tr>';
$('tbody').append(tr);
});
$('button.delete').on('click', function() {
var cRow = $(this).parents('tr');
var cId = $('td:nth-child(2)', cRow).text();
var intKey = $(this).data('key');
cRow.fadeOut('slow', function() {
doDelete(cId, intKey);
});
});
function doDelete(param1, param2) {
alert('Data with\n\nID: [' + param1 + ']\nKey: [' + param2 + ']\n\nRemoved.');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="1" width="100%">
<thead>
<tr>
<th>#</th>
<th>Id</th>
<th>Name</th>
<th>Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>

Is it possible to iterate through each item in an array and output as HTML?

I have a for loop that pushes targeted properties into an array if they pass a certain condition. I would like to create a table that outputs each item into its own row. The tricky part for myself is understanding how this can be done dynamically. It's easy to hardcode each item from the array and insert it into a row. But can this be done automatically using pure JS?
script.js
var myArray = [];
for (var i = 0; i < ccirdata.length; i++) {
if (ccirdata[i].catType === 'I') {
myArray.push(ccirdata[i].catNum);
}
};
In the same file,
I have the outline for my table where I'm trying to insert the iterations from 'myArray':
var header =
"<thead>" +
"<tr>" +
"<td class='legend-color-guide'><div style='background-color: " + series.color + ";'></div></td>" +
"<td class='key'>" + " My Table:</td>" +
"</tr>" +
"</thead>";
var rows =
"<tr>" +
"<td class='key'><strong>" + <INSERT HERE> + "</strong></td>" +
"</tr>"
return "<table>" + header + "<tbody>" + rows +"</tbody>" + "</table>";
How can I create a new row dynamically for each item in myArray?
Here's one approach:
// using the same header code you provided
var rows = "";
myArray.forEach(function(item, index) {
rows += "<tr>";
rows += "<td class='key'><strong>" + item + "</strong></td>";
rows += "</tr>";
});
return "<table>" + header + "<tbody>" + rows +"</tbody>" + "</table>";
You can loop through myArray to create each row and concatenate them into a larger string.
var rows = "";
for (var r = 0; r < myArray.length; r++) {
var row = "<tr>" + "<td class='key'><strong>" + myArray[r] + "</strong></td></tr>";
rows = rows.concat(row);
}
Instead of building a text string to later set as HTML, I would opt for using a cleaner approach with insertRow like this:
<table>
<thead>
<tr><td>A header</td></tr>
</thead>
<tbody>
</tbody>
</table>
<script type="text/javascript">
var values = ['foo', 'bar', 'baz']; // Values to insert in table
// Get a reference to the <tbody> element
var tbody = document.querySelector('tbody');
for (var i = 0; i < values.length; i++) {
// This appends a new row to the <tbody> and returns a reference
// to that element
var row = tbody.insertRow();
// Similarly to append a cell to the row
var cell = row.insertCell();
// Create a text node for the textual content and append it
// to the cell
var text = document.createTextNode(values[i]);
cell.appendChild(text);
}
</script>
As demonstrated in this JSFiddle.

JQuery Drag and Drop from two tables

I need to implement drag and drop feature form one table to another and vise versa.
This is my function where i get transactions to particular IBAN number, I also have the same function which retrieves users transaction which are hidden.
function getAllTransactions(iban) {
var iban = $("#ibanSelection").val();
var username = $("#hiddenusername").val();
var url = 'http://localhost:64300/api/BankAccountApi/GetUserTransaction/?iban=' + iban;
var table = "<table id=\"table1\">";
if ((username != "") && (iban !="")) {
$.getJSON(url, function (data) {
table += "<tr class=\"ibanSelection\">";
table += "<th>My IBAN</th>";
table += "<th>Send to IBAN</th>";
table += "<th>Transfer Date</th>";
table += "<th>Amount</th>";
table += "</tr>";
$.each(data, function (key, val) {
table += "<tr class=\"draggable_tr\">";
table += "<td>" + val.My_Iabn + "</td>";
table += "<td>" + val.Iban_To + "</td>";
table += "<td>" + val.Transfer_Date + "</td>";
table += "<td>" + val.Amount_Transferd + "</td>";
table += "</tr>";
});
table += "</table>";
$("#divResult2").html(table);
});
}
}
Just use the jQueryUI Sortable feature.
Here's the complete example + documentation. Very easy.
Also this example shows your case:
http://jqueryui.com/sortable/#connect-lists

JSON objects and HTML tables

First time poster here and new to JavaScript...
Below is my JSON object...
[
{
"Name":"Ted",
"EmailAddress":"ted#ted.edu",
"Title":"Director",
"Expertise":"Statistics",
"PhoneNumber":"444-444-4444"
},
{
"Name":"Ann",
"EmailAddress":"ann#ann.edu",
"Title":"Director",
"Expertise":"Physics",
"PhoneNumber":"444-444-5555"
}
]
What I need is to be able to loop through this to add each table row for each employee. There are five values: Name, EmailAddress, Title, Expertise, PhoneNumber
This is what I have so far...
$(function () {
var Employees= [{"Name":"Ted","EmailAddress":"ted#ted.edu","Title":"Director","Expertise":"Statistics","PhoneNumber":"444-444-4444"}, {"Name":"Ann","EmailAddress":"ann#ann.edu","Title":"Director","Expertise":"Physics","PhoneNumber":"444-444-5555"}];
$("#pager").append("<table id='employeelist' class='table'><table>");
//for loop goes here//
Any help would be appreciated!
EDIT: Also, how would I make the e-mail addresses 'clickable'/'mail to' the address?
A simple loop will do, you should also build the entire HTML string, then append:
var table = "<table id='employeelist' class='table'>";
for (var i = 0; i < Employees.length; i++) {
//Create the table row
table += "<tr>";
//Create table cells
table += "<td>" + Employees[i].Name + "</td>";
table += "<td>" + Employees[i].EmailAddress + "</td>";
table += "<td>" + Employees[i].Title + "</td>";
table += "<td>" + Employees[i].Expertise + "</td>";
table += "<td>" + Employees[i].PhoneNumber + "</td>";
//Close table row
table += "</tr>";
}
table += "</table>";
$("#pager").append(table);
Since JSON objects are just normal Javascript objects, you can treat them as such.
For example, in order to loop over them you could just do normal Javascript loop:
for(var i = 0; i < Employees.length; i++) {
var employee = Employees[i];
}
and then, in order to access information from an employee, you can just do employee.Name to access it's name, employee.Title for the title etc.
Using the information in employee.Name and the others, you can simply build your strings using that information:
str += '<td>' + employee.Name + ...
and then finally append it with $("#pager").append(str);.
'Welcome to Stackoverflow and javascript :)'
It is actually a javascript object ( not JSON object ).
$(function() {
var Employees = [{
"Name": "Ted",
"EmailAddress": "ted#ted.edu",
"Title": "Director",
"Expertise": "Statistics",
"PhoneNumber": "444-444-4444"
}, {
"Name": "Ann",
"EmailAddress": "ann#ann.edu",
"Title": "Director",
"Expertise": "Physics",
"PhoneNumber": "444-444-5555"
}];
var table = '<table id="employeelist" class="table">';
for (var i = 0, j = Employees.length; i < j; i++) {
table += '<tr>';
table += '<td>' + Employees[i].Name + '</td>';
table += '<td>' + Employees[i].EmailAddress + '</td>';
table += '<td>' + Employees[i].Title + '</td>';
table += '<td>' + Employees[i].Expertise + '</td>';
table += '<td>' + Employees[i].PhoneNumber + '</td>';
table += '</tr>';
}
table += '</table>';
$("#pager").append(table);
});
You are using jQuery. Then it should be something like this:
var table=$("<table>",{
id:"employeelist"
}).addClass("table");
table.appendTo($("#pager"));
$("#pager").append(table);
$.each(Employees, function(index, employee){
var row=$("<tr>",{});
$("<td>",{
html:employee.name
}).appendTo(row);
$("<td>",{
html:employee.EmailAddress
}).appendTo(row);
$("<td>",{
html:employee.Title
}).appendTo(row);
$("<td>",{
html:employee.Expertise
}).appendTo(row);
$("<td>",{
html:employee.PhoneNumber
}).appendTo(row);
row.appendTo(table);
});

How to pass id of dynamic drop downlist?

I have dynamic table, in that table every row has a dynamic dropdown list. So every dynamic dropdown list have a unique id, I have to pass this id to the onChange function. Please tell me how to do this. Please see this question for more info.
<select id=carpender"+obj[i].b_id +"onChange='update(this.id)
The data in the table is dynamically generated. I have to pass an id like carpenter12, if the value of obj[i].b_id is 12.
Working code I modified this code
JavaScript:
<script>
function fetchData1(){
$(".data-contacts1-js tbody").empty();
$.get("http://localhost/service/services.php", function(data) {
var obj=JSON.parse(data);
// convert it into obj otherwise it will give
//alert(obj.length);
for(var i in data){
var tr=$("<tr></tr>");
tr.append(
"<td>" + obj[i].b_id + "</td>" +
"<td>" + obj[i].cust_name + "</td>" +
"<td>" + obj[i].cust_mobile + "</td>" +
"<td>" + obj[i].cust_email + "</td>");
tr.append("<select id="+obj[i].b_id+" onChange='update(this.id)' class='input-small'><option value='New Job'>New Job</option><option value='WIP Job'>WIP Job</option><option value='Close Job'>Close Job</option></select>");
$(".data-contacts1-js tbody").append(tr);
i++;
}
});
}
$(document).ready(function(){
$(".data-contacts1-js tbody").empty();
$('#fetchContacts1').click(function() {
fetchData1();
});
});
</script>
<script>
function update(id){
alert(id);
}
</script>

Categories