DRY - Loops that creates tables - javascript

Im storing data in arrays, from that arrays im creating table with loops. For one table I need two columns, for another 30 (depends on array items). This going to have three columns.
var prodej = [
/*First column, second, third column*/
["Jack", 100, 101],
["Bkack", 100, 5],
["Duck", 100, 9],
];
And here is my loop
for ( var i = 0; prodej.length > i; i += 1) {
var tr = '<tr>'
var td1 = '<td>' + prodej[i][0]; + '</td>'
var td2 = '<td>' + prodej[i][1]; + '</td>'
var td3 = '<td>' + prodej[i][2]; + '</td>'
tr += td1 + td2 + td3 + '</tr>'
$("#firstTable").append(tr);
}
And here is another array and loop for it
var another = [
["Buick", 100],
["Ford", 100],
["Nissan", 100],
];
for ( var i = 0; another.length > i; i += 1) {
var tr = '<tr>'
var td1 = '<td>' + another[i][0]; + '</td>'
var td2 = '<td>' + another[i][1]; + '</td>'
tr += td1 + td2 + '</tr>'
$("#secondTable").append(tr);
}
I see a lot of same code, but I don't know what can I do for to have just one loop. Goals is
get lenght of inner array and based on that create same number td in tr
create unique id bassed on array name

You could write a function that takes the array and the id as arguments. Use nested loops to create the cells.
function createTable(data, id) {
for (var i = 0; data.length > i; i += 1) {
var tr = '<tr>';
for (var j = 0; data[i].length > j; j += 1) {
tr += '<td>' + data[i][j]; + '</td>';
}
tr += '</tr>';
$("#" + id).append(tr);
}
}
Then you can call this function when you want to create your table:
createTable(prodej, 'firstTable');
createTable(another, 'secondTable');

You can use the table api:
function populateTable(table, rowsData) {
rowsData.forEach(function(rowData) {
var row = table.insertRow();
rowData.forEach(function(cellData) {
var cell = row.insertCell();
var text = document.createTextNode(cellData);
cell.appendChild(text);
});
});
}
var prodej = [
["Jack", 100, 101],
["Bkack", 100, 5],
["Duck", 100, 9]
];
var table1 = document.getElementById('table1');
populateTable(table1, prodej);
var another = [
["Buick", 100],
["Ford", 100],
["Nissan", 100]
];
var table2 = document.getElementById('table2');
populateTable(table2, another);
<table id="table1"></table>
<br />
<br />
<table id="table2"></table>

You can write a function that will test to see how long the array is, then how long the current element of the array is. You can then reuse the function passing it an array and a table to append too.
var prodej = [
/*First column, second, third column*/
["Jack", 100, 101],
["Bkack", 100, 5],
["Duck", 100, 9],
];
var another = [
["Buick", 100],
["Ford", 100],
["Nissan", 100],
];
var myTable = $('#firstTable');
DRYLoop(another, myTable);
function DRYLoop(array, table) {
for (var i = 0; array.length > i; i += 1) {
table.append('<tr>');
for (var d = 0; d < array[i].length; d++) {
table.append('<td>' + array[i][d] + '</td>');
}
table.append('</tr>');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="firstTable">
</table>

Related

Create new <tr>as text after 3rd <td> in JS

i want to create new table row as text <tr> after every third table data<td> from user input.
It have to be like this:
<table border="3" align="center" style="width: 100%;">
<tr>
<td><a href="link"><img src="link"></td>
<td><a href="lin"><img src="link"></td>
<td><a href="link"><img src="link"></td>
</tr>
<tr>
<td><a href="link"><img src="link"></td>
<td><a href="lin"><img src="link"></td>
<td><a href="link"><img src="link"></td>
</tr>
</table>
My code:
<script type="text/javascript">
let x = 0;
const data = Array();
document.getElementById('btn').addEventListener("click", fun);
function fun() {
var val = document.getElementById('imagename').value;
source = val;
img = document.createElement('img');
img.src = source;
document.body.appendChild(img);
// move child to up
var before = document.getElementById('before');
before.insertBefore(img, before.children[0]);
/*var html = document.getElementById('before').innerHTML;
document.getElementById('code').innerHTML = '<img src=' + src + '>';*/
document.getElementById('code').innerText = '<img src="' + source + '">';
data[x] = document.getElementById('imagename').value;
x++;
}
document.getElementById('pasteBtn').addEventListener("click", makeCode);
function makeCode(){
let resultData = "<tr>";
for (let i = 0; i < data.length; i++){
resultData += "<td>" + '<a href="' + data[i] + '">' + '<img src="' + data[i] + '"></td>\n';
if(i % 3 == 0){
resultdata += '</tr><tr>';
}
}
cssText = 'tr {width: 100%; display: flex;} td {width: 100%;}';
tableText = '\n<table border="3" align="center" style="width: 100%;">\n';
document.getElementById("paste").innerText = "<style>" + cssText + "</style>" + tableText + resultData;
}
</script>
I was trying with modulo but nothing happened. It have to be done in JS, not JQuery.
Your code has a couple of problems, which have been mentioned in the comments. The last created row is not closed. Some browsers nowadays automatically solve this problem by adding the closing tag for that row, but it leaves you with a floating row.
A second problem is your modulo calculation. Since javascript arrays start at 0 and not at 1 you modulo creates the row to early, for:
0 % 3 = 0
1 % 3 = 1
2 % 3 = 2
3 % 3 = 0
A row is created containing ONLY the first value. This can be fixed by changing the modulo calculation to i + 1 % 3, however it might not immediatly be clear why you seemingly randomly add the 1.
Another option is to introduce a counter. It is clear what the counter does, it counts. It is also clear to where it counts, 3. By moving the closing and starting of the row to before the adding of the cell you prevent floating rows. You only start a new row, when you actually need one. Important still is to close the row, but as said before, there are browsers that do this, but you should not rely on that.
let resultData = "<tr>";
let counter = 0;
for (let i in data){
if(counter == 3){
resultdata += '</tr><tr>';
counter = 0;
}
resultData += "<td>" + '<a href="' + data[i] + '">' + '<img src="' + data[i] + '"></td>\n';
counter++;
}
resultdata += "</tr>";
Personally I prefer to use a for...in loop for looping over an array, but that is personal preference
There are many ways to accomplish what you are looking for.
For my answer I chunked the array into groups of 3, then I loop through each element in each group.
I also chose to use createElement instead of using the string versions.
let table = document.querySelector("#paste");
let data = [
1,2,3,4,5,6,7,8,9
];
while((row = data.splice(0, 3)).length){
let tr = document.createElement("tr");
for(z=0;z<=row.length-1;z++){
let td = document.createElement("td");
let link = document.createElement("a");
let img = document.createElement("img");
img.src = row[z];
link.href = row[z];
link.appendChild(img)
td.appendChild(link)
tr.appendChild(td)
}
table.appendChild(tr)
}
<table id="paste"></table>
Adding EventListener to MakeCode.Btn.getting the count of td each row has with data.length/3(9/3=3);so each row will have 3 td's.
Creating index variable to iterate over the array.
creating Two ForLoops.
1st loop will create a row with an id of r(i).first row will have an id of id="r1".
2nd loop will get the row that was created in the first loop and it will add td tCount times which is 3 in this case.
& data will also be added inside each td with ${data[index]}
incrementing the index every time a td is added.
when index is equal to data.length getting the innerHtml of the table and pasting it in the text area as a value.and setting the innerHtml of the actual table to "" empty
const data = [
"hello",
"world",
"code",
"coding",
"javascript",
"css",
"html",
"react",
"scss"
];
let table = document.getElementById("table");
let btn = document.getElementById("pasteBtn");
let textBox = document.getElementById("textbox");
btn.addEventListener("click", () => {
let tdCount = data.length / 3;
let index = 0;
for (let i = 1; i <= 3; i++) {
table.innerHTML += `<tr id="r${i}"></tr>`;
for (let j = 1; j <= tdCount; j++) {
document.getElementById(`r${i}`).innerHTML += `<td><a href="link"><img src="link"></td>`;
index++;
if (index === data.length) {
let finalHtml = document.getElementById("table").innerHTML;
textBox.value = finalHtml;
document.getElementById("table").innerHTML = "";
}
}
}
});
textarea {
width: 100%;
height: 200px;
}
<button id="pasteBtn">makeCode</button>
<table border="3" align="center" style="width: 100%;">
<tbody id="table">
</tbody>
</table>
<textarea id="textbox"></textarea>
As mentioned #imvain2's answer, it is better to use js document.createElement over the string to create the elements. And here is an approach that uses a single loop.
HTML:
<table id="data-table"></table>
const data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const table = document.getElementById('data-table');
const addRows = (data) => {
let tableRow = null;
data.forEach((item, index) => {
// adds a new row on first and then after every third "td"
if (index % 3 === 0) {
tableRow = document.createElement('tr');
tableRow.id = 'tr' + (index + 1);
table.appendChild(tableRow);
}
const tableData = document.createElement('td');
tableRow.appendChild(tableData);
const link = document.createElement('a');
link.href = item;
link.title = item;
tableData.appendChild(link);
const img = document.createElement('img');
img.src = item;
link.appendChild(img);
});
};
addRows(data);

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/

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

Creating html table using Javascript not working

Basically, I want the user the just change the 'height' variable to how ever many rows he wants, and then store the words which each td in the row should contain, and the code should then generate the table.
My html is just this:
<table id="newTable">
</table>
This is my Javascript:
<script type="text/javascript">
var height = 2; // user in this case would want 3 rows (height + 1)
var rowNumber = 0;
var height0 = ['HeadingOne', 'HeadingTwo']; // the words in each td in the first row
var height1 = ['firstTd of row', 'secondTd of row']; // the words in each td in the second row
var height2 = ['firstTd of other row', 'secondTd of other row']; // the words in each td in the third row
$(document).ready( function() {
createTr();
});
function createTr () {
for (var h=0; h<height + 1; h++) { // loop through 3 times, in this case (which h<3)
var theTr = "<tr id='rowNumber" + rowNumber + "'>"; // <tr id='rowNumber0'>
$('#newTable').append(theTr); // append <tr id='rowNumber0'> to the table
for (var i=0; i<window['height' + rowNumber].length; i++) {
if (i == window['height' + rowNumber].length-1) { // if i==2, then that means it is the last td in the tr, so have a </tr> at the end of it
var theTd = "<td class='row" + rowNumber + " column" + i + "'>" + window['height' + rowNumber][i] + "</td></tr>";
$('#rowNumber' + rowNumber).append(theTr); // append to the end of the Tr
} else {
var theTd = "<td class='row" + rowNumber + " column" + i + "'>" + window['height' + rowNumber][i] + "</td>";
$('#rowNumber' + rowNumber).append(theTr);
}
}
rowNumber += 1;
}
}
</script>
I did 'alert(theTr);' and 'alert(theTd);' and they looked correct. How come this code doesn't generate any table?
You should change the line
$('#rowNumber' + rowNumber).append(theTr);
into
$('#rowNumber' + rowNumber).append(theTd);
You are adding the Tr-Code again in the inner loop, but you actually wanted to add the Td-Code.
All that window["height"+rowNumber] stuff is a poor way to do it. Use an array, and pass it as a parameter to the function so you don't use global variables. And use jQuery DOM creation functions instead of appending strings.
<script type="text/javascript">
var heights = [['HeadingOne', 'HeadingTwo'], // the words in each td in the first row
['firstTd of row', 'secondTd of row'], // the words in each td in the second row
['firstTd of other row', 'secondTd of other row'] // the words in each td in the third row
];
$(document).ready( function() {
createTr(heights);
});
function createTr (heights) {
for (var h=0; h<heights.length; h++) { // loop through 3 times, in this case (which h<3)
var theTr = $("<tr>", { id: "rowNumber" + h});
for (var i=0; i<heights[h].length; i++) {
theTr.append($("<td>", { "class": "row"+h + " column"+i,
text: heights[h][i]
}));
}
$('#newTable').append(theTr); // append <tr id='rowNumber0'> to the table
}
}
</script>
JSFIDDLE

Create table with jQuery - append

I have on page div:
<div id="here_table"></div>
and in jquery:
for(i=0;i<3;i++){
$('#here_table').append( 'result' + i );
}
this generating for me:
<div id="here_table">
result1 result2 result3 etc
</div>
I would like receive this in table:
<div id="here_table">
<table>
<tr><td>result1</td></tr>
<tr><td>result2</td></tr>
<tr><td>result3</td></tr>
</table>
</div>
I doing:
$('#here_table').append( '<table>' );
for(i=0;i<3;i++){
$('#here_table').append( '<tr><td>' + 'result' + i + '</td></tr>' );
}
$('#here_table').append( '</table>' );
but this generate for me:
<div id="here_table">
<table> </table> !!!!!!!!!!
<tr><td>result1</td></tr>
<tr><td>result2</td></tr>
<tr><td>result3</td></tr>
</div>
Why? how can i make this correctly?
LIVE: http://jsfiddle.net/n7cyE/
This line:
$('#here_table').append( '<tr><td>' + 'result' + i + '</td></tr>' );
Appends to the div#here_table not the new table.
There are several approaches:
/* Note that the whole content variable is just a string */
var content = "<table>"
for(i=0; i<3; i++){
content += '<tr><td>' + 'result ' + i + '</td></tr>';
}
content += "</table>"
$('#here_table').append(content);
But, with the above approach it is less manageable to add styles and do stuff dynamically with <table>.
But how about this one, it does what you expect nearly great:
var table = $('<table>').addClass('foo');
for(i=0; i<3; i++){
var row = $('<tr>').addClass('bar').text('result ' + i);
table.append(row);
}
$('#here_table').append(table);
Hope this would help.
You need to append the tr inside the table so I updated your selector inside your loop and removed the closing table because it is not necessary.
$('#here_table').append( '<table />' );
for(i=0;i<3;i++){
$('#here_table table').append( '<tr><td>' + 'result' + i + '</td></tr>' );
}
The main problem was that you were appending the tr to the div here_table.
Edit: Here is a JavaScript version if performance is a concern. Using document fragment will not cause a reflow for every iteration of the loop
var doc = document;
var fragment = doc.createDocumentFragment();
for (i = 0; i < 3; i++) {
var tr = doc.createElement("tr");
var td = doc.createElement("td");
td.innerHTML = "content";
tr.appendChild(td);
//does not trigger reflow
fragment.appendChild(tr);
}
var table = doc.createElement("table");
table.appendChild(fragment);
doc.getElementById("here_table").appendChild(table);
When you use append, jQuery expects it to be well-formed HTML (plain text counts). append is not like doing +=.
You need to make the table first, then append it.
var $table = $('<table/>');
for(var i=0; i<3; i++){
$table.append( '<tr><td>' + 'result' + i + '</td></tr>' );
}
$('#here_table').append($table);
Or do it this way to use ALL jQuery. The each can loop through any data be it DOM elements or an array/object.
var data = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight'];
var numCols = 1;
$.each(data, function(i) {
if(!(i%numCols)) tRow = $('<tr>');
tCell = $('<td>').html(data[i]);
$('table').append(tRow.append(tCell));
});
​
http://jsfiddle.net/n7cyE/93/
To add multiple columns and rows, we can also do a string concatenation. Not the best way, but it sure works.
var resultstring='<table>';
for(var j=0;j<arr.length;j++){
//array arr contains the field names in this case
resultstring+= '<th>'+ arr[j] + '</th>';
}
$(resultset).each(function(i, result) {
// resultset is in json format
resultstring+='<tr>';
for(var j=0;j<arr.length;j++){
resultstring+='<td>'+ result[arr[j]]+ '</td>';
}
resultstring+='</tr>';
});
resultstring+='</table>';
$('#resultdisplay').html(resultstring);
This also allows you to add rows and columns to the table dynamically, without hardcoding the fieldnames.
Here is what you can do: http://jsfiddle.net/n7cyE/4/
$('#here_table').append('<table></table>');
var table = $('#here_table').children();
for(i=0;i<3;i++){
table.append( '<tr><td>' + 'result' + i + '</td></tr>' );
}
Best regards!
Following is done for multiple file uploads using jquery:
File input button:
<div>
<input type="file" name="uploadFiles" id="uploadFiles" multiple="multiple" class="input-xlarge" onchange="getFileSizeandName(this);"/>
</div>
Displaying File name and File size in a table:
<div id="uploadMultipleFilediv">
<table id="uploadTable" class="table table-striped table-bordered table-condensed"></table></div>
Javascript for getting the file name and file size:
function getFileSizeandName(input)
{
var select = $('#uploadTable');
//select.empty();
var totalsizeOfUploadFiles = "";
for(var i =0; i<input.files.length; i++)
{
var filesizeInBytes = input.files[i].size; // file size in bytes
var filesizeInMB = (filesizeInBytes / (1024*1024)).toFixed(2); // convert the file size from bytes to mb
var filename = input.files[i].name;
select.append($('<tr><td>'+filename+'</td><td>'+filesizeInMB+'</td></tr>'));
totalsizeOfUploadFiles = totalsizeOfUploadFiles+filesizeInMB;
//alert("File name is : "+filename+" || size : "+filesizeInMB+" MB || size : "+filesizeInBytes+" Bytes");
}
}
Or static HTML without the loop for creating some links (or whatever). Place the <div id="menu"> on any page to reproduce the HTML.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>HTML Masterpage</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript">
function nav() {
var menuHTML= '<ul><li>link 1</li></ul><ul><li>link 2</li></ul>';
$('#menu').append(menuHTML);
}
</script>
<style type="text/css">
</style>
</head>
<body onload="nav()">
<div id="menu"></div>
</body>
</html>
I wrote rather good function that can generate vertical and horizontal tables:
function generateTable(rowsData, titles, type, _class) {
var $table = $("<table>").addClass(_class);
var $tbody = $("<tbody>").appendTo($table);
if (type == 2) {//vertical table
if (rowsData.length !== titles.length) {
console.error('rows and data rows count doesent match');
return false;
}
titles.forEach(function (title, index) {
var $tr = $("<tr>");
$("<th>").html(title).appendTo($tr);
var rows = rowsData[index];
rows.forEach(function (html) {
$("<td>").html(html).appendTo($tr);
});
$tr.appendTo($tbody);
});
} else if (type == 1) {//horsantal table
var valid = true;
rowsData.forEach(function (row) {
if (!row) {
valid = false;
return;
}
if (row.length !== titles.length) {
valid = false;
return;
}
});
if (!valid) {
console.error('rows and data rows count doesent match');
return false;
}
var $tr = $("<tr>");
titles.forEach(function (title, index) {
$("<th>").html(title).appendTo($tr);
});
$tr.appendTo($tbody);
rowsData.forEach(function (row, index) {
var $tr = $("<tr>");
row.forEach(function (html) {
$("<td>").html(html).appendTo($tr);
});
$tr.appendTo($tbody);
});
}
return $table;
}
usage example:
var title = [
'مساحت موجود',
'مساحت باقیمانده',
'مساحت در طرح'
];
var rows = [
[number_format(data.source.area,2)],
[number_format(data.intersection.area,2)],
[number_format(data.deference.area,2)]
];
var $ft = generateTable(rows, title, 2,"table table-striped table-hover table-bordered");
$ft.appendTo( GroupAnalyse.$results );
var title = [
'جهت',
'اندازه قبلی',
'اندازه فعلی',
'وضعیت',
'میزان عقب نشینی',
];
var rows = data.edgesData.map(function (r) {
return [
r.directionText,
r.lineLength,
r.newLineLength,
r.stateText,
r.lineLengthDifference
];
});
var $et = generateTable(rows, title, 1,"table table-striped table-hover table-bordered");
$et.appendTo( GroupAnalyse.$results );
$('<hr/>').appendTo( GroupAnalyse.$results );
example result:
A working example using the method mentioned above and using JSON to represent the data. This is used in my project of dealing with ajax calls fetching data from server.
http://jsfiddle.net/vinocui/22mX6/1/
In your html:
< table id='here_table' >< /table >
JS code:
function feed_table(tableobj){
// data is a JSON object with
//{'id': 'table id',
// 'header':[{'a': 'Asset Tpe', 'b' : 'Description', 'c' : 'Assets Value', 'd':'Action'}],
// 'data': [{'a': 'Non Real Estate', 'b' :'Credit card', 'c' :'$5000' , 'd': 'Edit/Delete' },... ]}
$('#' + tableobj.id).html( '' );
$.each([tableobj.header, tableobj.data], function(_index, _obj){
$.each(_obj, function(index, row){
var line = "";
$.each(row, function(key, value){
if(0 === _index){
line += '<th>' + value + '</th>';
}else{
line += '<td>' + value + '</td>';
}
});
line = '<tr>' + line + '</tr>';
$('#' + tableobj.id).append(line);
});
});
}
// testing
$(function(){
var t = {
'id': 'here_table',
'header':[{'a': 'Asset Tpe', 'b' : 'Description', 'c' : 'Assets Value', 'd':'Action'}],
'data': [{'a': 'Non Real Estate', 'b' :'Credit card', 'c' :'$5000' , 'd': 'Edit/Delete' },
{'a': 'Real Estate', 'b' :'Property', 'c' :'$500000' , 'd': 'Edit/Delete' }
]};
feed_table(t);
});
As for me, this approach is prettier:
String.prototype.embraceWith = function(tag) {
return "<" + tag + ">" + this + "</" + tag + ">";
};
var results = [
{type:"Fiat", model:500, color:"white"},
{type:"Mercedes", model: "Benz", color:"black"},
{type:"BMV", model: "X6", color:"black"}
];
var tableHeader = ("Type".embraceWith("th") + "Model".embraceWith("th") + "Color".embraceWith("th")).embraceWith("tr");
var tableBody = results.map(function(item) {
return (item.type.embraceWith("td") + item.model.toString().embraceWith("td") + item.color.embraceWith("td")).embraceWith("tr")
}).join("");
var table = (tableHeader + tableBody).embraceWith("table");
$("#result-holder").append(table);
i prefer the most readable and extensible way using jquery.
Also, you can build fully dynamic content on the fly.
Since jquery version 1.4 you can pass attributes to elements which is, imho, a killer feature.
Also the code can be kept cleaner.
$(function(){
var tablerows = new Array();
$.each(['result1', 'result2', 'result3'], function( index, value ) {
tablerows.push('<tr><td>' + value + '</td></tr>');
});
var table = $('<table/>', {
html: tablerows
});
var div = $('<div/>', {
id: 'here_table',
html: table
});
$('body').append(div);
});
Addon: passing more than one "html" tag you've to use array notation like:
e.g.
var div = $('<div/>', {
id: 'here_table',
html: [ div1, div2, table ]
});
best Rgds.
Franz
<table id="game_table" border="1">
and Jquery
var i;
for (i = 0; ii < 10; i++)
{
var tr = $("<tr></tr>")
var ii;
for (ii = 0; ii < 10; ii++)
{
tr.append(`<th>Firstname</th>`)
}
$('#game_table').append(tr)
}
this is most better
html
<div id="here_table"> </div>
jQuery
$('#here_table').append( '<table>' );
for(i=0;i<3;i++)
{
$('#here_table').append( '<tr>' + 'result' + i + '</tr>' );
for(ii=0;ii<3;ii++)
{
$('#here_table').append( '<td>' + 'result' + i + '</tr>' );
}
}
$('#here_table').append( '</table>' );
It is important to note that you could use Emmet to achieve the same result. First, check what Emmet can do for you at https://emmet.io/
In a nutshell, with Emmet, you can expand a string into a complexe HTML markup as shown in the examples below:
Example #1
ul>li*5
... will produce
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
Example #2
div#header+div.page+div#footer.class1.class2.class3
... will produce
<div id="header"></div>
<div class="page"></div>
<div id="footer" class="class1 class2 class3"></div>
And list goes on. There are more examples at https://docs.emmet.io/abbreviations/syntax/
And there is a library for doing that using jQuery. It's called Emmet.js and available at https://github.com/christiansandor/Emmet.js
Here the below code helps to generate responsive html table
#javascript
(function($){
var data = [{
"head 1": "row1 col 1",
"head 2": "row1 col 2",
"head 3": "row1 col 3"
}, {
"head 1": "row2 col 1",
"head 2": "row2 col 2",
"head 3": "row2 col 3"
}, {
"head 1": "row3 col 1",
"head 2": "row3 col 2",
"head 3": "row3 col 3"
}];
for (var i = 0; i < data.length; i++) {
var accordianhtml = "<button class='accordion'>" + data[i][small_screen_heading] + "<span class='arrow rarrow'>→</span><span class='arrow darrow'>↓</span></button><div class='panel'><p><table class='accordian_table'>";
var table_row = null;
var table_header = null;
for (var key in data[i]) {
accordianhtml = accordianhtml + "<tr><th>" + key + "</th><td>" + data[i][key] + "</td></tr>";
if (i === 0 && true) {
table_header = table_header + "<th>" + key + "</th>";
}
table_row = table_row + "<td>" + data[i][key] + "</td>"
}
if (i === 0 && true) {
table_header = "<tr>" + table_header + "</tr>";
$(".mv_table #simple_table").append(table_header);
}
table_row = "<tr>" + table_row + "</tr>";
$(".mv_table #simple_table").append(table_row);
accordianhtml = accordianhtml + "</table></p></div>";
$(".mv_table .accordian_content").append(accordianhtml);
}
}(jquery)
Here we can see the demo responsive html table generator
let html = '';
html += '<table class="tblWay" border="0" cellpadding="5" cellspacing="0" width="100%">';
html += '<tbody>';
html += '<tr style="background-color:#EEEFF0">';
html += '<td width="80"> </td>';
html += '<td><b>Shipping Method</b></td>';
html += '<td><b>Shipping Cost</b></td>';
html += '<td><b>Transit Time</b></td>';
html += '</tr>';
html += '</tbody>';
html += '</table>';
$('.product-shipping-more').append(html);

Categories

Resources