Making table and it's content via JavaScript - javascript

Hw to download arr content into the table cells from left to right and from up to down? What is wrong with my code? How to solve the problem? Thanks in advance.
<button onclick="myFunction()></button>
<table id="myTable" border='1px'>
<tr>
<th>N</th>
<th>Name</th>
<th>Surname</th>
<th>tel.</th>
<th>email</th>
</tr>
</table>
var arr=[[1,2,3,4,'a'],[5,6,7,8,'b'],[9,10,11,12,'c']];
function myFunction() {
createTable();
}
function createTable(){
var i,j;
var table = document.getElementById("myTable");
for( i=0; i<arr.length; i++ ) {
var row = table.insertRow(1);
for( j=0,k=0; j<5, k<arr[i].length;j++, k++ ) {
var cell = row.insertCell(0);
cell.innerHTML = arr[i][k];
}
}
}

Well i am not sure about your data structure but if you get your data in the following form.
[ { N: 1, Name: 2, Surname: 3, Tel: 4, email: 'a' },
{ N: 5, Name: 6, Surname: 7, Tel: 8, email: 'b' },
{ N: 9, Name: 10, Surname: 11, Tel: 12, email: 'c' } ]
You can use the following tableMaker function. It will take the properties as headers (if second argument is provided as true) and values as corresponding cells to generate an HTML text. So here it goes as follows;
var tableMaker = (o,h) => {var keys = o.length && Object.keys(o[0]),
rowMaker = (a,t) => a.reduce((p,c,i,a) => p + (i === a.length-1 ? "<" + t + ">" + c + "</" + t + "></tr>"
: "<" + t + ">" + c + "</" + t + ">"),"<tr>"),
rows = o.reduce((r,c) => r + rowMaker(keys.reduce((v,k) => v.concat(c[k]),[]),"td"),h ? rowMaker(keys,"th") : []);
return rows.length ? "<table>" + rows + "</table>" : "";
},
arr = [[1,2,3,4,'a'],[5,6,7,8,'b'],[9,10,11,12,'c']],
tableObj = arr.map(e => ({N: e[0], Name: e[1], Surname : e[2], Tel: e[3], email: e[4]})),
tableHTML = tableMaker(tableObj,true);
document.write(tableHTML);

Related

Removing Data Javascript

I use an array of object to display data on a dynamic table I create with javascript
inside the table, there are 2 button delete and edit
when I press the delete I delete the data from the array but for some reason, the data still remains in the table ? can someone give me a clue why?
workers = [{
name: 'Roni',
phone: '0545931252',
nickname: 'RoniBoy',
mail: 'Roni#gmail.com',
},
{
name: 'Lior',
phone: '0545996452',
nickname: 'LiorBoy',
mail: 'Lior#gmail.com',
},
{
name: 'Arman',
phone: '0545886452',
nickname: 'ArmanBoy',
mail: 'Arman#gmail.com',
}
];
function deleteFromList(id) {
workers.splice(id, 1);
console.log(workers);
}
const toAppend = document.getElementById('appendBox');
let markup = '';
for (let x = 0; x < workers.length; x++) {
markup += `<tr>
<td >` + workers[x].name + `</td>
<td>` + workers[x].nickname + `</td>
<td>` + workers[x].phone + `</td>
<td>` + workers[x].mail + `</td>
<td><button onClick="deleteFromList(this.id)" id="` + x + `" class="btn btn-danger">Remove</button> <button class="btn btn-success">Edit</button></td>
</tr>`
}
toAppend.innerHTML = markup;
<table id="appendBox"></table>
You have rerender html every time you update you array
workers = [
{
name: 'Roni',
phone: '0545931252',
nickname: 'RoniBoy',
mail: 'Roni#gmail.com',
},
{
name: 'Lior',
phone: '0545996452',
nickname: 'LiorBoy',
mail: 'Lior#gmail.com',
},
{
name: 'Arman',
phone: '0545886452',
nickname: 'ArmanBoy',
mail: 'Arman#gmail.com',
}
];
function deleteFromList(id){
workers.splice(id,1);
console.log(workers);
renderMarkup();
}
function renderMarkup() {
const toAppend = document.getElementById('appendBox');
let markup = '';
for(let x = 0; x < workers.length; x++){
markup += `
<tr>
<td >`+workers[x].name+`</td>
<td>`+workers[x].nickname+`</td>
<td>`+workers[x].phone+`</td>
<td>`+workers[x].mail+`</td>
<td><button onClick="deleteFromList(this.id)" id="`+x+`" class="btn btn-danger">Remove</button> <button class="btn btn-success">Edit</button></td>
</tr>`
}
toAppend.innerHTML = markup;
}
renderMarkup();
<table id="appendBox"></table>
If you want to remove stuff from your table then you might want to add some sequential IDs to each row so that you can directly delete one. You could also do something like this just grabbing one in the spot it's in and delete it that way. Are you looking to delete rows or are you just trying to delete a column in a row?
var tblBody = document.getElementById("tblBody"); //referencing a <tbody> tag's id
var row = document.getElementsByTagName("tr"); //get every tr element
tblBody.deleteRow(row[i].rowIndex);

Converting JSON array in HTML table using JQuery

My JSON Array containing date and key-value pairs of alphabets. I need columns as date values and rows heading as Alphabets.
{
"error":0,
"data":[
{
"date":"2017-12-01",
"A":1,
"B":2
},
{
"date":"2017-12-02",
"A":2,
"B":3
}
]
}
I want to create table as given below
Alpha 2017-12-01 2017-12-02
A 1 2
B 2 3
My HTML Code containing datatable for table formatting:
<table id="report" class="table table-striped table-bordered">
<thead>
<tr>
<th>Alpha</th>
</tr>
</thead>
<tbody></tbody>
</table>
And JQuery ajax get response that calls the API:
$.ajax({
url: 'userData/01/2018',
success: function(response) {
let reportData = response.data;
let i = 0;
let j = 1;
let k = 0;
let table = document.getElementById('report');
let tr = table.tHead.children[0];
reportData.forEach(function(data) {
let row = table.insertRow(j);
if (i == 0) {
let th = document.createElement('th');
th.innerHTML = data.date;
tr.appendChild(th);
}
if (k == 0) {
let keys = Object.keys(data);
for (let p = 1; p < keys.length; p++) {
let cell = row.insertCell(k);
cell.innerHTML = keys[p];
for (let q = 1; q < keys.length; q++) {}
}
}
});
}
});
I am able to insert headers as table columns but facing an issue in data insertion.
slight changes in your json string,
HTML:
<table id="report"></table>
JavaScript:
var jsonString = '{"error": 0,"Alpha": [{"date": "2017-12-01","A": 1,"B": 2},{"date": "2017-12-02","A": 2,"B": 3}]}';
var s = '';
$.each(JSON.parse(jsonString), function(i, j) {
if (i == 'Alpha') {
s += '<thead><th>' + i + '</th>';
$.each(j, function(k, val) {
s += '<th>' + val.date + '</th>';
});
s += '</thead>';
$('#report').html(s);
for (var l = 0; j.length; l++) {
if (l == 0) {
s = '<tbody><tr><td> ' + Object.keys(j[l])[l + 1] + ' </td>';
s += '<td> ' + j[l].A + ' </td><td>' + j[l].B + '</td></tr>';
$('#report').append(s);
} else {
s = '<tr><td>' + Object.keys(j[l])[l + 1] + '</td><td>' + j[l].A + '</td><td>' + j[l].B + '</td></tr>';
$('#report').append(s);
}
s += '</tbody>';
}
}
});
For reference - https://jsfiddle.net/zvxqf9mz/

JQuery adding and saving data input in row

I am having trouble saving the new row. When i click on add person I am able to input the data, however, i am not sure how to save it and add a new row.
I know i have to make a function for the save button to work however i am stuck on how to make it work. I have tried a few times but to no avail.
var isNewLineToggled = false;
var isAscending = {
name : false,
lastName: false,
dob: false
};
$(".main").append("<input placeholder='search by name' class='search'/><br/><br/>")
$(".main").append("<button onclick=addPerson()>add a person</button><br/><br/>")
var table = $(".main").append("<table></table>");
var thead = '<thead><tr></tr></thead>';
table.append(thead);
var header = [
{ title: 'Name', sortBy: 'name'},
{ title: 'Last Name', sortBy: 'lastName'},
{ title: 'Date of birth', sortBy: 'dob'}
].map(
function(header) {
var sortButton = '<button id="' + header.sortBy + '" onclick=sortRows("'+ header.sortBy + '")>/\\</button>';
$('thead').append('<th>' + header.title + ' ' + sortButton + '</th>');
}
)
var tbody = "<tbody></tbody>";
var data = [ {name: 'Peter', lastName: 'Petterson', dob: '13/12/1988'},
{name: 'Anna', lastName: 'Jones', dob: '06/02/1968'},
{name: 'John', lastName: 'Milton', dob: '01/06/2000'},
{name: 'James', lastName: 'White', dob: '30/11/1970'},
{name: 'Luke', lastName: 'Brown', dob: '15/08/1999'}
];
$('.search').change(function(event) {
searchedName = event.target.value;
})
table.append(tbody);
data.map(
function(row, i) {
$('tbody').append(
'<tr><td>' + row.name +
'</td><td>' + row.lastName +
'</td><td>' + row.dob +
'</td><td><button onclick=editRow('+i+')>edit</button><button>delete</button></td></tr>'
)
}
)
var editableRow = "<td><input/></td><td><input/></td><td><input type='date'/></td><td><button onclick=saveRow()>save</button></td>";
var addPerson = function() {
isNewLineToggled = !isNewLineToggled;
if (isNewLineToggled) {
$('tbody').prepend('<tr>' + editableRow + '</tr>')
} else {
$('tbody > tr:first-child').remove();
}
}
var editRow = function(rowNumber) {
var name = $('tbody > tr:nth-child('+(rowNumber + 1)+') > td:first-child').text();
var lastName = $('tbody > tr:nth-child('+(rowNumber + 1)+') > td:nth-child(2)').text();
var dob = $('tbody > tr:nth-child('+(rowNumber + 1)+') > td:nth-child(3)').text();
$('tbody > tr:nth-child('+(rowNumber + 1)+')').html(editableRow2);
$('tbody > tr:nth-child('+(rowNumber + 1)+') > td:first-child > input').val(name);
$('tbody > tr:nth-child('+(rowNumber + 1)+') > td:nth-child(2) > input').val(lastName);
}
You can add row like this, two small changes:
$(".main").append("<button class='add'>add a person</button><br/><br/>")
Remove inline event handler, no need for it. And your function could be:
$('body').on('click','.add', function() { //you will need event delegation, because of dynamically added elements
isNewLineToggled = !isNewLineToggled;
if (isNewLineToggled) {
$('tbody').prepend('<tr>' + editableRow + '</tr>')
} else {
$('tbody > tr:first-child').remove();
}
});
Since your editableRow variable isn't defined, i've used just one cell with text for demo:
https://jsfiddle.net/2c97auey/1/
P.S. Your editableRow should have input(s) values, properly placed in cells. Shouldn't be too hard.

Populating a table with an object with JQuery

I have an array of objects object [{Date, Count, City}]
Lets say I have this data
[{01/01/01, 10, New York}, {01/01/01, 15, London}, {01/01/01, 16, Rome},{02/01/01, 40, New York},{02/01/01, 25, London}, {02/01/01, 36, Rome}]
I want to populate an html table using JQuery and have the following result
Date | New York | London | Rome
01/01/01 | 10 | 15 | 16
02/01/01 | 40 | 25 | 36
Is it possible to generate a table similar to this with JQuery?
This is the code I have done so far
for (var i = 0; i < countResult.length; i++) {
var html = "<table><thead><tr><th>Date</th><th>City</th><th>Count</th></thead><tbody>";
for (var j = 0; j < countResult[i].length; j++) {
html += "<tr>";
html += "<td>" + countResult[i][j].date + "</td><td>" + countResult[i][j].city + "</td><td>" + countResult[i][j].count+ "</td>";
}
html += "</tr>";
html += "</tbody></table></br>";
$(html).appendTo("#div");
}
The solution for my question was:
var countResult = [
["01/01/01", 10, "New York"],
["01/01/01", 15, "London"],
["01/01/01", 16, "Rome"],
["02/01/01", 40, "New York"],
["02/01/01", 25, "London"],
["02/01/01", 36, "Rome"]
]
var cities = []
$.each(countResult, function(rowNum, row) {
var city = row[2];
if($.inArray(city, cities) < 0) cities.push(city);
});
var html = "<table><thead><tr><th>Date</th>"
+ $.map(cities, function (c) {
return "<th>" + c
}).join("") + "</tr></thead><tbody>";
var summary = {};
$.each(countResult, function
(rowNum, row) {
if(!summary[row[0]]) summary[row[0]] = {}
summary[row[0]][row[2]] = row[1];
});
$.each(summary, function (date, counts) {
html += "<tr><td>" + date;
$.each(counts, function (i, ct) {
html += "<td>" + ct ;
});
html += "</tr>";
});
$(html).appendTo("#div");
Try this code
var html='<table>';
var arObj = YOUR ARRAY OBJECT;
$(arObj).each(function(i, u) {
var Date = u[0];
var count = u[1];
var City=u[2];
html=html+'<tr><td>'+Date+'</td><td>'+count+'</td><td>'+City+'</td><td>';
});
html=html+'</table>';
Now append to html
$('#myDiv').append(html);

Slicing an array into several chunks

Please take a look at this fiddle.
How can I slice an array into several small arrays
var data =
[ { number: '1' },
{ number: '2' },
{ number: '3' },
{ number: '4' },
{ number: '5' },
{ number: '6' },
{ number: '7' },
{ number: '8' },
{ number: '9' },
{ number: '10'}
];
and build a table for each of them?
Example:
<table>
<thead>
<tr>
<th>Number</th><th>Number</th><th>Number</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td><td>2</td><td>3</td>
</tr>
</tbody>
</table>
<table>
<thead>
<tr>
<th>Number</th><th>Number</th><th>Number</th>
</tr>
</thead>
<tbody>
<tr>
<td>4</td><td>5</td><td>6</td>
</tr>
</tbody>
</table>
........
The following code isn't working. The output is kind of a mess. As you can see in the fiddle, I can't access the key(number), and there are empty <table></table> tags in between the tables. Can anyone show me how to slice the array properly.
Code:
var data = [ { number: '1' },
{ number: '2' },
{ number: '3' },
{ number: '4' },
{ number: '5' },
{ number: '6' },
{ number: '7' },
{ number: '8' },
{ number: '9' },
{ number: '10'}
];
var chunks = [];
var item_html ="";
for (var i=0; i<data.length; ) {
chunks.push(data.slice(i, i+=3));
}
for (var i=0; i<chunks.length; i++) {
item_html += "<table><thead><tr>";
(i, chunks[i].map(function(key,v){
item_html += "<th>"+key+"</th>";
}));
item_html += "</tr></thead><tbody><tr>";
(i, chunks[i].map(function(v){
item_html += "<td>"+v.number+"</td>";
}));
item_html += "</tr></tbody><table>";
}
$('#area').append(item_html)
The incorrect headings are because you have the arguments to the iteration function in the wrong order in the first .map() call. The first argument is the value, the second argument is the key. It should be:
chunks[i].map(function (v, key) {
The empty tables are because of a typo. This line:
item_html += "</tr></tbody><table>";
should be:
item_html += "</tr></tbody></table>";
You were missing the / in </table>.
The corrected loop is:
for (var i = 0; i < chunks.length; i++) {
item_html += "<table><thead><tr>";
chunks[i].map(function (v, key) {
item_html += "<th>" + key + "</th>";
});
item_html += "</tr></thead><tbody><tr>";
chunks[i].map(function (v) {
item_html += "<td>" + v.number + "</td>";
});
item_html += "</tr></tbody></table>";
}
There was no point to the extra (i, ...) that you had around each call to .map(), so I removed it.
Updated fiddle

Categories

Resources