Convert array of objects into HTML table with jQuery or Javascript - javascript

How can I convert the following Javascript array of object
[{"firstName":"John", "last Name":"Doe", "age":"46"},
{"firstName":"James", "last Name":"Blanc", "age":"24"}]
Into HTML table like below
<table>
<tr>
<th>firstName</th>
<th>last Name</th>
<th>age</th>
</tr>
<tr>
<td>John</td>
<td>Doe</tD>
<td>46</th>
</tr>
<tr>
<td>James</td>
<td>Blanc</tD>
<td>24</th>
</tr>
</table>
Thanks in advance.

You can do this using forEach method , which accepts as parameter a callback provided function.
var users=[{"firstName":"John", "last Name":"Doe", "age":"46"},
{"firstName":"James", "last Name":"Blanc", "age":"24"}]
users.forEach(function(item){
$('tbody').append('<tr><td>'+item.firstName+'</td><td>'+item["last Name"]+'</td><td>'+item.age+'</td></tr>')
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>firstName</th>
<th>last Name</th>
<th>age</th>
</tr>
</thead>
<tbody>
</tbody>
</table>

Try this code:
var rows = [{"firstName":"John", "last Name":"Doe", "age":"46"},
{"firstName":"James", "last Name":"Blanc", "age":"24"}];
var html = '<table>';
html += '<tr>';
for( var j in rows[0] ) {
html += '<th>' + j + '</th>';
}
html += '</tr>';
for( var i = 0; i < rows.length; i++) {
html += '<tr>';
for( var j in rows[i] ) {
html += '<td>' + rows[i][j] + '</td>';
}
html += '</tr>';
}
html += '</table>';
document.getElementById('container').innerHTML = html;
<div id="container">
</div>

In your HTML put below code
<div id="myTable">
</div>
And in script put below code
var arrObj = [{"firstName":"John", "lastName":"Doe", "age":"46"},
{"firstName":"James", "lastName":"Blanc", "age":"24"}]
var objLength = arrObj.length;
var myvar = '<table>'+
'<tr>'+
'<th>firstName</th>'+
'<th>last Name</th>'+
'<th>age</th>'+
'</tr>';
for(var i = 0; i < objLength; i++){
myvar += '<tr>'+
'<td>'+arrObj[i].firstName+'</td>'+
'<td>'+arrObj[i].lastName+'</tD>'+
'<td>'+arrObj[i].age+'</th>'+
'</tr>'
}
myvar += '</table>';
console.log(myvar);
document.getElementById('myTable').innerHTML = myvar;
Hope this works

Related

HTML CSS how to make a dynamic multicolumn table from a 2D table with JavaScript

I would like to make a dynamic multicolumn table from a static 2D table, like the picture below (see solution):
The correct HTML-code as folows:
<div class="container">
<table border='1' id='theTable'>
<thead>
<tr>
<th>Name</th>
<th>Role</th>
</tr>
</thead>
<tbody>
<tr>
<td>Adam</td>
<td>AAA</td>
</tr>
<tr>
<td>Adam</td>
<td>BBB</td>
</tr>
<tr>
<td>Adam</td>
<td>CCC</td>
</tr>
<tr>
<td>Bert</td>
<td>AAA</td>
</tr>
<tr>
<td>Bert</td>
<td>CCC</td>
</tr>
<tr>
<td>Cesar</td>
<td>BBB</td>
</tr>
</tbody>
</table>
<br>
<table id='newTable' border='1'>
<thead></thead>
<tbody></tbody>
</table>
</div>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
$(document).ready(function () {
var role_arr = [];
$("#theTable td:nth-child(2)").each(function() {
if ($.inArray($(this).text(), role_arr) == -1)
role_arr.push($(this).text());
});
role_arr.sort()
console.log(role_arr);
// create thead row and put Roles in it
var trow = "<tr>";
trow += '<th>Name</th>';
for (var i=0; i<role_arr.length; i++) {
trow +='<th>'+ role_arr[i] +'</th>';
}
trow += '</tr>';
$("#newTable").find("thead").append(trow);
// create all names array
var name_arr = [];
$("#theTable td:nth-child(1)").each(function() {
if ($.inArray($(this).text(), name_arr) == -1)
name_arr.push($(this).text());
});
console.log(name_arr);
for (var i=0; i<name_arr.length; i++) {
// create an array for each name's roles
var row_arr = [];
$("#theTable tr:has(td:contains('"+name_arr[i]+"'))").each(function () {
//console.log($(this).find('td:nth-child(2)').text());
row_arr.push($(this).find('td:nth-child(2)').text());
});
// create the table body row row
var trow = "<tr>";
trow += '<td>'+name_arr[i]+'</td>';
for(var j=0; j<role_arr.length; j++) {
if(row_arr.includes(role_arr[j])) {
trow += '<td> X </td>';
}
else {
trow += '<td> - </td>';
}
}
trow += '</tr>';
$("#newTable").find("tbody").append(trow);
}
});
</script>
I used jquery to iterate through the table. First created all different roles array and then individual names array. Then created individual rows for each names. I have added comments in the code.
<div class="container">
<table border='1' id='theTable'>
<thead>
<tr>
<th>Name</th>
<th>Role</th>
</tr>
</thead>
<tbody>
<tr>
<td>Adam</td>
<td>AAA</td>
</tr>
<tr>
<td>Adam</td>
<td>BBB</td>
</tr>
<tr>
<td>Adam</td>
<td>CCC</td>
</tr>
<tr>
<td>Bert</td>
<td>AAA</td>
</tr>
<tr>
<td>Bert</td>
<td>CCC</td>
</tr>
<tr>
<td>Cesar</td>
<td>BBB</td>
</tr>
</tbody>
</table>
<br>
<table id='newTable' border='1'>
<thead></thead>
<tbody></tbody>
</table>
</div>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
$(document).ready(function () {
var role_arr = [];
$("#theTable td:nth-child(2)").each(function() {
if ($.inArray($(this).text(), role_arr) == -1)
role_arr.push($(this).text());
});
console.log(role_arr);
// create thead row and put Roles in it
var trow = "<tr>";
trow += '<th>Name</th>';
for (var i=0; i<role_arr.length; i++) {
trow +='<th>'+ role_arr[i] +'</th>';
}
trow += '</tr>';
$("#newTable").find("thead").append(trow);
// create all names array
var name_arr = [];
$("#theTable td:nth-child(1)").each(function() {
if ($.inArray($(this).text(), name_arr) == -1)
name_arr.push($(this).text());
});
console.log(name_arr);
for (var i=0; i<name_arr.length; i++) {
// create an array for each name's roles
var row_arr = [];
$("#theTable tr:has(td:contains('"+name_arr[i]+"'))").each(function () {
//console.log($(this).find('td:nth-child(2)').text());
row_arr.push($(this).find('td:nth-child(2)').text());
});
// create the table body row row
var trow = "<tr>";
trow += '<td>'+name_arr[i]+'</td>';
for(var j=0; j<role_arr.length; j++) {
if(row_arr.includes(role_arr[j])) {
trow += '<td> X </td>';
}
else {
trow += '<td> - </td>';
}
}
trow += '</tr>';
$("#newTable").find("tbody").append(trow);
}
});
</script>

Populating local storage data to an HTML table?

After creating a game and implementing scores etc, I have saved the current logged in player's username along with his score to local storage.
/*Saves current logged in player to local storage*/
let player = sessionStorage.getItem("loggedInUsername");
function savePlayer(){
/*sets logged in player + score + time*/
let Player = [player, score];
localStorage.setItem("Player",Player.toString());
}
I then call the function once the game is over. I have also created a high score table in HTML like so:
<body class = "score">
<article>
<!-- Table for TopScores -->
<table align = "center">
<tr>
<td id= "title" colspan = "3"><h1>Top Scores</h1></td>
</tr>
<tr>
<th>Username</th>
<th>Score</th>
<th>Time</th>
</tr>
<tr>
<td></td>
<td></td>
<td>0</td>
</tr>
<tr>
<td></td>
<td></td>
<td>0</td>
</tr>
<tr>
<td></td>
<td></td>
<td>0</td>
</tr>
</table>
</article>
</body>
I am having difficulty calling the player's username and his score to the high score table using localStorage.getItem.
Any help would be much appreciated.
You can create table row data from javascript, find below code snippet of jsfiddle link (https://jsfiddle.net/59u4ba0d/):
HTML:
<table>
<tbody id="tbody"></tbody>
</table>
Javascript:
var testObject = [{ 'name': 'James', 'score': 90, 'time': '16:00' }, {
'name': 'Robert', 'score': 80, 'time': '15:00' }];
localStorage.setItem('testObject', JSON.stringify(testObject));
var retrievedObject = JSON.parse(localStorage.getItem('testObject'));
var tbody = document.getElementById('tbody');
for (var i = 0; i < retrievedObject.length; i++) {
var tr = "<tr>";
tr += "<td>Name</td>" + "<td>" + retrievedObject[i].name + "</td></tr>";
tr += "<td>Score</td>" + "<td>" + retrievedObject[i].score + "</td></tr>";
tr += "<td>Time</td>" + "<td>" + retrievedObject[i].time + "</td></tr>";
tbody.innerHTML += tr;
}

Dynamic table with bootstrap

I'm trying to do dynamic table with bootstrap but I can't deduce why it's not working. There's a HTML part:
<div class="container">
<button onclick="CreateTable()">Extend</button>
<table class="table">
<thead>
<tr>
<th>Employee Id</th>
<th>Name</th>
<th>Country</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>John Doe</td>
<td>Country1</td>
</tr>
<tr>
<td>2</td>
<td>Mary Moe</td>
<td>Country2</td>
</tr>
<tr>
<td>3</td>
<td>Jack Dooley</td>
<td>Country3</td>
</tr>
<p id="id_tabela"></p>
</tbody>
</table>
</div>
and there's javascript:
function CreateTable() {
var employee = new Array();
employee.push([4, "Billie Jean", "Country4"]);
employee.push([5, "Harish Kumar", "Country5"]);
employee.push([6, "Pankaj Mohan", "Country6"]);
employee.push([7, "Nitin Srivastav", "Country7"]);
employee.push([8, "Ramchandra Verma", "Country8"]);
var tablecontents = "";
for (var i = 0; i < employee.length; i++) {
tablecontents += "<tr>";
for (var j = 0; j < employee[i].length; j++) {
tablecontents += "<td>" + employee[i][j] + "</td>";
}
tablecontents += "</tr>";
}
document.getElementById("id_tabela").innerHTML = tablecontents;
}
So I want to extend the table and I can't figure out why it's not working.
You are loading the data inside the paragraph, which is not what you want to do. Also the paragraph shouldn't be there. You can add an id to tbody and then just extend its innerHTML like so: https://jsfiddle.net/14pt76wp/.
Why are you using native functions? bootstrap has jQuery included. You could do something like:
$('table tbody').append(tablecontents);
Another trick:
Iterate over the array and do employee[i] = '<td>' + employee[i].join('</td><td>') + '</td>';
tablecontents = '<tr>' + employee.join('</tr><tr>') + '</tr>';

How to get checked checkbox table value in jquery

In my table I have 2 rows please see my screen shot,suppose I click first check box means I want to take that id ** and **to_area value in jquery how can do this,I tried but I can not get please help some one
$(document).ready(function() {
$('#chemist_allotment_btn').click(function() {
if ($('#chemist_allotment_form').valid()) {
$.ajax({
url: 'update_chemist_bulk_transfer.php',
type: 'POST',
data: $('form#chemist_allotment_form').serialize(),
success: function(data) {
var res = jQuery.parseJSON(data); // convert the json
console.log(res);
if (res['status'] == 1) {
var htmlString = '';
$.each(res['data'], function(key, value) {
htmlString += '<tr>';
htmlString += ' <td class="sorting_1"><div class="checkbox-custom checkbox-success"><input type="checkbox" id="checkboxExample3" name="getchemist" class="getchemist" value="' + value.id + '"><label for="checkboxExample3"></label></div></td>';
htmlString += '<td>' + value.id + '</td>';
htmlString += '<td>' + value.name + '</td>';
htmlString += '<td>' + value.area + '</td>';
htmlString += '<td>' + value.to_area + '</td>';
htmlString += '<td>' + value.address + '</td>';
htmlString += '</tr>';
});
$('#SampleDT tbody').empty().append(htmlString);
$('#get_to_area').click(function() {
var id = $('input[name=getchemist]:checked').val();
if ($(".getchemist").prop('checked') == true) {
alert(id);
alert(value.to_area);
} else {
alert('Please Check');
}
});
} else {
$('#SampleDT tbody').empty().append('No Datas Found');
}
},
});
return false;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="well white">
<table id="SampleDT" class="datatable table table-hover table-striped table-bordered tc-table">
<thead>
<tr>
<th>Select</th>
<th>Id</th>
<th>Doctor Name</th>
<th>From Area</th>
<th>To Area</th>
<th>Address</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<center>
<div class="form-group">
<button type="button" class="btn btn-primary" style="text-align:left;" id="get_to_area">Transfer Area</button>
</div>
</center>
</div>
Firstly, add classes to each <td>, like <td class='id'>[Your id]</td>
Similarly for all the elements doctor-name, to-area, etc and a class to each <tr> like row-select
Somewhat like this:
<tr class="row-select">
<td class="select">...</td>
<td class="id">...</td>
<td class="to-area">...</td>
.
.
.
</tr>
Use jQuery like this:
$('.row-select').click(function(){
var id,toArea,checkBox;
id = $(this).find('.id').html(); //get the ID field
toArea = $(this).find('.to-area').html(); //get the to-area field
checkBox = $(this).find('.select > input');
checkbox.prop('checked',!checkbox.prop('checked'));
})
This code will get you he value no mater where you click on the row, and also invert the selection on the checkbox
To get the values of rows selected when the form is submitted run a loop like this
$('.row-select input:checked').each(function(){
var id,toArea,checkBox;
id = $(this).closest('tr').find('.id').html(); //get the ID field
toArea = $(this).closest('tr').find('.to-area').html(); //get the to-area field
})
EDIT
All together:
$(document).ready(function() {
$('#btnSubmit').click(function() {
$('.row-select input:checked').each(function() {
var id, name;
id = $(this).closest('tr').find('.id').html();
name = $(this).closest('tr').find('.name').html();
alert('ID: ' + id + " | Name: " + name);
})
})
$('#btnSelectAll').click(function() {
$('.row-select input').each(function() {
$(this).prop('checked', true);
})
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border=1>
<tr class="row-select">
<td class="check">
<input type="checkbox" />
</td>
<td class="id">12</td>
<td class="name">Jones</td>
</tr>
<tr class="row-select">
<td class="check">
<input type="checkbox" />
</td>
<td class="id">10</td>
<td class="name">Joseph</td>
</tr>
</table>
<button id="btnSelectAll">Select all</button>
<button id="btnSubmit">Get Value</button>
Process step-by-step:
Give the td you need some classes (from-a & to-a);
Initialize an empty array all (we'll store the data inside it later on);
Create a function that is triggered by the checkbox change
Inside the function you need to know which checkbox has changed, what's the state of it, what tr does it belong to and at the end what are the TO AREA and FROM AREA values.
If the state = checked we will add the values to the all (our small data storage);
If the state = not-checked we will remove the value from the all array;
Finally when we are done with selecting and deselecting rows by pressing the button we can get the values of the selected rows.
var all = [];
$('input[type="checkbox"]').change(function(){
var checkbox = $(this);
var state = checkbox.prop('checked');
var tr = checkbox.parents('tr');
var from = tr.children('.from-a').text();
var to = tr.children('.to-a').text();
if(state){
all.push(from + ' -> ' + to);
}else{
var index = all.indexOf(from + ' -> ' + to);
all.splice(index, 1);
}
})
$('#get_to_area').click(function(){
alert(all);
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div class="well white">
<table id="SampleDT" class="datatable table table-hover table-striped table-bordered tc-table">
<thead>
<tr>
<th>Select</th>
<th>Id</th>
<th>Doctor Name</th>
<th>From Area</th>
<th>To Area</th>
<th>Address</th>
</tr>
</thead>
<tbody>
<tr id="1">
<td><input type="checkbox"></td>
<td>1</td>
<td>Nick</td>
<td class="from-a">Kosur</td>
<td class="to-a">Nath Pari</td>
<td>Address</td>
</tr>
<tr id="2">
<td><input type="checkbox"></td>
<td>2</td>
<td>John</td>
<td class="from-a">Rusok</td>
<td class="to-a">iraP htaN</td>
<td>sserddA</td>
</tr>
</tbody>
</table>
<center>
<div class="form-group">
<button style="text-align:left;" id="get_to_area">Transfer Area</button>
</div>
</center>
</div>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</body>
</html>
This is just the basic concept, you can modify it to suit your needs, I'll be happy to help you if you get stuck.
You can also use this fiddle:
In JS:
$('#get_to_area').click(function () {
var id = $('input[name=getchemist]:checked').val();
if ($('input[name=getchemist]').is(':checked')) {
var ID = $('input[name=getchemist]').parent().parent().siblings('td.chkid').html();
var TO_Area = $('input[name=getchemist]').parent().parent().siblings('td.toarea').html();
}
else {
alert('Please Check');
}
});
In Html:
if (res['status'] == 1) {
var htmlString = '';
$.each(res['data'], function (key, value) {
htmlString += '<tr>';
htmlString += ' <td class="sorting_1"><div class="checkbox-custom checkbox-success"><input type="checkbox" id="checkboxExample3" name="getchemist" class="getchemist" value="' + value.id + '"><label for="checkboxExample3"></label></div></td>';
htmlString += '<td class="chkid">' + value.id + '</td>';
htmlString += '<td>' + value.name + '</td>';
htmlString += '<td>' + value.area + '</td>';
htmlString += '<td class="toarea">' + value.to_area + '</td>';
htmlString += '<td>' + value.address + '</td>';
htmlString += '</tr>';
});
I'm guessing you need values of each td whose checbox are checked. This piece of code should get you started.
As you can see, Code loops through each checkbox which is checked, gets contents inside its corresponding td.
var Result = new Array();
$('.checkbox-custom input[type="checkbox"]:checked').each(function(){
var _this = $(this).closest('tr').find('td');
var id= $(_this).eq(0);
var name = $(_this).eq(1);
................... //Similar way for the others
Result.Push(id,name,....)
});

Controlling table with JS

I have written a very simple code
<!DOCTYPE html>
<html>
<body>
<table id="myTable" border = "1"></table>
<script>
for(var i = 1; i<=5; i++){
var tableRow = "<tr>";
tableRow+= "<td>" + "JS Table" + "</td>";
tableRow+= "</tr>";
}
document.getElementById("myTable").innerHTML = tableRow;
</script>
</body>
</html>
I want to generate a table like this code snippet
<table border = "1">
<tr>
<td>JS Table</td>
</tr>
<tr>
<td>JS Table</td>
</tr>
<tr>
<td>JS Table</td>
</tr>
<tr>
<td>JS Table</td>
</tr>
<tr>
<td>JS Table</td>
</tr>
</table>
But it's giving only one row while I have set for loop for 5 times. How to solve this.
I am facing one more problem. If I write javascript in head tag, I don;t get any output & it's saying "document.getElementById("myTable").innerHTML" is null. How to rectify it?
<!DOCTYPE html>
<html>
<head>
<script>
for(var i = 1; i<=5; i++){
var tableRow = "<tr>";
tableRow+= "<td>" + "JS Table" + "</td>";
tableRow+= "</tr>";
}
document.getElementById("myTable").innerHTML = tableRow;
</script>
</head>
<body>
<table id="myTable"></table>
</body>
</html>
Problem 1
The problem is that you are overriding your tableRow again and again in the for loop. So, you need to move that outside the for loop. You will need to update your script to
var tableRow = ""; // moved outside the loop
for(var i = 1; i<=5; i++){
tableRow += "<tr>"; // appending <tr>
tableRow+= "<td>" + "JS Table" + "</td>";
tableRow+= "</tr>";
}
document.getElementById("myTable").innerHTML = tableRow;
Problem 2
The issue is coming because you are trying to execute the code before the dom is rendered. Try it wrap it inside the onload function i.e.
window.onload = function(){
// your code here
};
For reference - https://developer.mozilla.org/en/docs/Web/API/GlobalEventHandlers/onload
<!DOCTYPE html>
<html>
<head>
<script>
window.onload = function(){
var tableRow = "";
for(var i = 1; i<=5; i++){
tableRow += "<tr>";
tableRow += "<td>" + "JS Table" + "</td>";
tableRow += "</tr>";
}
document.getElementById("myTable").innerHTML = tableRow;
};
</script>
</head>
<body>
<table id="myTable"></table>
</body>
</html>
var tableRow="";
for(var i = 1; i<=5; i++){
tableRow += "<tr>";
tableRow+= "<td>" + "JS Table" + "</td>";
tableRow+= "</tr>";
}
document.getElementById("myTable").innerHTML = tableRow;
<table id="myTable"></table>

Categories