Table Not Populating as I expected using Jquery - javascript

I am trying to populate a table using a JSON file. When I run this through the browser, my first row populates. However the other rows do not. Can someone please point out to me what I am doing wrong? Am I not looping this correctly? Thank you in advance.
$(document).ready(function() {
$.getJSON( "data.json", function(data) {
var htmlToRender= [];
var item;
for (var i = 0; i < data.length; i++) {
item = data[i];
console.log(data[i]);
htmlToRender = '<tr><td>' + item.name + '</td>'
'<td>' + item.description + '</td>'
console.log(item.description)
'<td>Open In Google Mapspwd</td></tr>';
console.log(item.location);
$('#hot-spots').append(htmlToRender);
console.log(htmlToRender);
};
});
});

The lines following htmlToRender = '<tr><td>' + item.name + '</td>' look a bit suspicious--you're missing a + sign to concatenate these additional strings, and sprinkled console.logs amidst the string build isn't helping the cause.
I recommend using a string template:
const item = {
name: "hello",
description: "world",
location: "somewhere"
};
const htmlToRender = `
<tr>
<td>${item.name}</td>
<td>${item.description}</td>
<td>
Open In Google Maps
</td>
</tr>
`;
$('#hot-spots').append(htmlToRender);
table {
border-collapse: collapse;
}
td {
border: 1px solid black;
padding: 0.5em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="hot-spots"></table>

Related

Table not appending cells from array

I am trying to append these cells to a dynamic table, and fill the child Labels with text from an array.
I am not getting any errors. Only one cell with the oldest data is displayed.
for (i=0; i < response.array.length; i++) {
console.log(response.array[i].Sender)
$('.name').html(response.array[i].Sender);
$('.date').html(response.array[i].Date);
$('.subject').html(response.array[i].Subject);
cell.append(name);
cell.append(date);
cell.append(subject);
$('#table').append(cell);
}
EDIT:
I have tried this method, but I can't move the Labels inside the cell
for (i=0; i < response.array.length; i++) {
trHTML += '<tr><td>' + response.array[i].Sender + '<td><td>' + response.array[i].Date +'<td><td>' + response.array[i].Subject + '<td><tr>'
}
EDIT 2:
I have tried this, and the first cell is display correctly but the other data is display as [object Object][object Object][object Object][object Object]
trHTML += $('.name').html(response.array[i].Sender) + $('.date').html(response.array[i].Date) + $('.subject').html(response.array[i].Subject);
In this line...
trHTML += '<tr><td>' + response.array[i].Sender + '<td><td>' + response.array[i].Date +'<td><td>' + response.array[i].Subject + '<td><tr>'
...you don't have any closing tags (like </td>after the cell contents and </tr> at the end of the row), only opening tags, which leads to invalid HTML and creates code that makes no sense for the browser.
The JSON posted in the comments was F.U.B.A.R.ed. There are 2 problems that make it inconsumable.
#
Description
⓵
There are a lot of smart quotes: “ and ”, I believe the only valid quotes used in JSON are double quotes ".
⓶
The last quote is missing and it's not because of a cut & paste job, because there's 2 objects and an array right side brackets placed properly.
So take that mess to a validator.
{“ // ⓵
dataarray”: [{“
Subject”: ”Delivery”,
”Date ":"
2022 - 06 - 02 17: 49: 36 ", "
Sender”: ”John”,
”user_id ":67890, "
Message”: ”This is the confirmation of your order”
}, {“
Subject”: ”Delivery”,
”Date ":"
2022 - 06 - 07 07: 31: 25 ", "
Sender”: ”James”,
”user_id ":67890, "
Message”: ”This is the confirmation of your order // ⓶
}]
}
After you fix that JSON or the endpoint or whatever. Do a simple test and past the url in the browser addressbar. If it works you'll see it displayed on an unstyled page. If you still can't get it going I noticed that in OP this is used:
response.array[i]
Normally the response is the entire JSON and whatever is connected to it is a property of said response so .array[i] is an Array called "array", but the only array in the JSON is called "dataarray"?
Details commented in example below
// Pass JSON
const buildTable = data => {
// Reference <tbody>
const table = document.querySelector('tbody');
/*
Loop to generate htmlString for each <tr>
filled with data fro JSON
*/
for (let i = 0; i < data.length; i++) {
let row = `<tr>
<td>${data[i].Sender}</td>
<td>${data[i].Date}</td>
<td>${data[i].Subject}</td>
</tr>`;
table.insertAdjacentHTML('beforeEnd', row);
}
};
// Pass endpoint of API
const getData = async(url) => {
// await fetch()
const response = await fetch(url);
// await JSON
const json = await response.json();
/*
Invoke buildTable to the first ten rows
*/
return buildTable(json);
};
// Runs at pageload
getData('https://my.api.mockaroo.com/misc.json?key=3634fcf0');
// Button bound to click event
document.querySelector('button').onclick = function() {
const url = 'https://my.api.mockaroo.com/misc.json?key=3634fcf0';
getData(url);
}
html {
font: 300 2ch/1 'Segoe UI'
}
table {
width: 90vw;
table-layout: fixed;
border-collapse: collapse;
}
th {
width: 30vw;
}
td {
border: 0.5px ridge grey;
padding: 5px;
}
button {
font: inherit;
float: right;
margin-top: 5px;
cursor: pointer;
}
<table>
<thead>
<tr>
<th>Sender</th>
<th>Date</th>
<th>Subject</th>
</tr>
</thead>
<tbody></tbody>
</table>
<button>GET 10 More</button>
I tried to work on this requirement and came up with the below working Demo :
let tableString = "<table>";
const response = {
array: [{
Sender: 'alpha',
Date: 'Date 1',
Subject: 'Subject 1'
}, {
Sender: 'Beta',
Date: 'Date 2',
Subject: 'Subject 2'
}, {
Sender: 'Gamma',
Date: 'Date 2',
Subject: 'Subject 2'
}]
}
tableString += `<tr>
<th>Sender</th>
<th>Date</th>
<th>Subject</th>
</tr>`;
for (i=0; i < response.array.length; i++) {
tableString += '<tr><td>' + response.array[i].Sender + '</td><td>' + response.array[i].Date +'</td><td>' + response.array[i].Subject + '</td></tr>'
}
tableString += "</table>";
$('#table').html(tableString);
table, th, td {
border: 1px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="table"></div>
Here is a compact version with dynamic property binding.
const response = {
array: [{
Sender: 'alpha',
Date: 'Date 1',
Subject: 'Subject 1'
}, {
Sender: 'Beta',
Date: 'Date 2',
Subject: 'Subject 2'
}, {
Sender: 'Gamma',
Date: 'Date 2',
Subject: 'Subject 2'
}]
}
let tableContainer = $('#table'),
table = $('<table>');
table.append('<tr><th>Sender</th><th>Date</th><th>Subject</th></tr>');
response.array.forEach(obj => {
const tr = $('<tr>');
['Sender', 'Date', 'Subject'].forEach(attr => {
tr.append('<td>' + obj[attr] + '</td>');
});
table.append(tr);
});
tableContainer.append(table);
table, th, td {
border: 1px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="table"></div>

html onclick not happening when parameter has special characters like $ or [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I have a code in which I have three rows with three parameters $COKE, COKE, COKE.
Every row has a sublist which opens when I click the parameters. It works fine when parameter doesnt have any special characters i.e.
For case when $COKE is parameter it doesn't open sublist onclick. ($ dollar sign)
For case when COKE is parameter it opens sublist onclick.
For case when COKE. is parameter it doesn't open sublist onclick. (. dot sign)
data[i].parameter="$COKE"
document.getElementById("results").innerHTML += "<tr id="+data[i].parameter+" onclick='showSublist(this.id)'>
data[i].paramater can have values as shown below $COKE, COKE.,COKE as an example.
Image shown as reference, where only case 2 opens but case 1 and case 3 doesn't open when I click them.
Cases Image
By not escaping special characters you are creating invalid HTML code, that's why onclick doesn't work.
Here is example how browser handles special characters:
function escape(a) {
return "&#" + a.charCodeAt(0) + ";";
}
function escapeText(text) {
return text.replace(/["'&<>]/g, escape);
}
function showSublist(id) {
alert(id);
}
var data = [{
parameter: "test"
},
{
parameter: "$test"
},
{
parameter: "<test"
},
{
parameter: "test>"
},
{
parameter: "<test>"
},
{
parameter: '"test'
},
{
parameter: 'test"'
},
{
parameter: '"test"'
},
{
parameter: "test."
},
{
parameter: '&test'
},
{
parameter: '&test;'
},
{
parameter: "test${test}"
},
];
for (let i = 0, tr = document.createElement("tr"); i < data.length; i++) {
tr = tr.cloneNode(false);
tr.innerHTML = '<td class="n">' + i + '</td>';
/* original, incorrect structure */
tr.innerHTML += "<td id=" + data[i].parameter + " onclick='showSublist(this.id)'>" + data[i].parameter + '</td>';
tr.innerHTML += '<td class="n">' + i + '</td>';
/* correct structure, no filter */
tr.innerHTML += '<td id="' + data[i].parameter + '" onclick="showSublist(this.id)">' + data[i].parameter + '</td>';
tr.innerHTML += '<td class="n">' + i + '</td>';
/* correct structure, filter */
tr.innerHTML += '<td id="' + escapeText(data[i].parameter) + '" onclick="showSublist(this.id)">' + escapeText(data[i].parameter) + '</td>';
tr.onmouseover = mouseOver;
document.getElementById("results").appendChild(tr);
};
var div = document.getElementById("html");
function mouseOver(e) {
html.textContent = e.target.className == "n" ? e.target.nextSibling.outerHTML : e.target.outerHTML;
}
th {
text-align: start;
}
td:nth-child(even) {
border-right: 1em solid transparent;
}
td:hover {
background-color: rgba(0, 0, 0, 0.1);
cursor: pointer;
}
div {
background-color: white;
color: black;
position: fixed;
bottom: 0;
margin-top: 1em;
padding: 0.5em;
border: 1px solid black;
}
table {
margin-bottom: 3em;
}
<table id="results">
<tr>
<th colspan="2">
Original, no quotes
</th>
<th colspan="2">
Unescaped
</th>
<th colspan="2">
Escaped
</th>
</tr>
</table>
<div id="html"></div>

how to get the value of the clicked table row?

My question is: how do I get the value of the clicked row and column?
The code I have is this:
JS:
$.ajax({
type: 'POST',
url: url,
data: json,
success: function(data) {
var response_array = JSON.parse(data);
var columns = ['id', 'name', 'email', 'telephone', 'website', 'city'];
var table_html = ' <tr>\n' +
'<th id="id">Id</th>\n' +
'<th id="name">Bedrijfnaam</th>\n' +
'<th id="email">E-mail</th>\n' +
'<th id="telephone">Telefoon</th>\n' +
'<th id="website">Website</th>\n' +
'<th id="city">Plaats</th>\n' +
'</tr>';
for (var i = 0; i < response_array.length; i++) {
//create html table row
table_html += '<tr>';
for (var j = 0; j < columns.length; j++) {
//create html table cell, add class to cells to identify columns
table_html += '<td class="' + columns[j] + '" >' + response_array[i][columns[j]] + '</td>'
}
table_html += '</tr>'
};
$("#posts").append(table_html);
},
error: function (jqXHR, textStatus, errorThrown) { alert('ERROR: ' + errorThrown); }
});
Here is the HTML:
<div class="tabel">
<table id="posts">
</table>
</div>
I have tried the following:
$('#posts').click(function(){
console.log("clicked");
var id = $("tr").find(".id").html();
console.log(id);
});
Sadly this will only give me the id of the first row, no matter where I click.
Any help is appreciated!
Ramon
The below approach should be able to find the ID
$('#post').on('click', function(e){
var id = $(e.target).closest('tr').find(".id").html();
console.log(id)
})
HTML content of clicked row
$('#posts tr').click(function(){
$(this).html();
});
text from clicked td
$('#posts tr td').click(function(){
$(this).text();
});
If you are using ajax and you are redrawing elements, you will not catch em via click function. You will need to add on function:
$(document).on('click','#posts tr td','function(){
$(this).text();
});
You may try to use AddEventListener for your table, it will work for sure.
Like this:
let posts = document.getlementById('posts');
posts.addEventListener('click',(e) => {
// anything you need here, for example:
console.log(e.target);
e.preventDefault();
});
As well - it will be fine not to use same IDs for elements in a grid (like id="id" which you have), it should be different.

getJSON JSON Array - Search Functionality Crashing Client

I'm running into a problem when trying to add in the search functionality, showList().
It seems to bog down the client so much that Chrome wants to kill the page each time I type into the input field. I'm clearly a novice JS writer, so could I be running an infinite loop somewhere I don't see? Also, any advice to get the search functionality working properly would be hugely appreciated. I don't think I'm using the correct selectors below for the show/hide if statement, but I can't think what else to use.
$(document).ready(function(){
showList();
searchBar();
});
function showList() {
$("#show-records").click(function(){
$.getJSON("data.json", function(data){
var json = data;
$("show-list").append("<table class='specialists'>")
for(var i = 0; i < json.length; i++) {
var obj = json[i],
tableFormat = "</td><td>";
$("#show-list").append("<tr><td class=1>" +
obj.FIELD1 + tableFormat +
obj.FIELD2 + tableFormat +
obj.FIELD3 + tableFormat +
obj.FIELD4 + tableFormat +
obj.FIELD5 + tableFormat +
obj.FIELD6 + tableFormat +
obj.FIELD7 + tableFormat +
obj.FIELD8 + "</td></tr>");
$("show-list").append("</table>");
}
//end getJSON inner function
});
//end click function
});
//end showList()
};
function searchBar() {
//AJAX getJSON
$.getJSON("data.json", function(data){
//gathering json Data, sticking it into var json
var json = data;
for(var i = 0; i < json.length; i++) {
//putting the json objects into var obj
var obj = json[i];
function contains(text_one, text_two) {
if (text_one.indexOf(text_two) != -1)
return true;
}
//whenever anything is entered into search bar...
$('#search').keyup(function(obj) {
//grab the search bar content values and...
var searchEntry = $(this).val().toLowerCase();
//grab each td and check to see if it contains the same contents as var searchEntry - if they dont match, hide; otherwise show
$("td").each(function() {
if (!contains($(this).text().toLowerCase(), searchEntry)) {
$(this).hide(400);
} else {
$(this).show(400);
};
})
})
}
});
};
body {
background-color: lightblue;
}
tr:first-child {
font-weight: bold;
}
td {
padding: 3px;
/*margin: 10px;*/
text-align: center;
}
td:nth-child(6) {
padding-left: 50px;
}
td:nth-child(7) {
padding-left: 10px;
padding-right: 10px;
}
#filter-count {
font-size: 12px;
}
<html>
<head>
<script language="javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script language="javascript" src="process.js"></script>
<link rel="stylesheet" type="text/css" href="./mystyle.css">
</head>
<body>
<a href="#" id='show-records'>Show Records</a><br>
<label id="searchBar">Search: <input id="search" placeholder="Enter Specialist Name"></label>
<span id="search-count"></span>
<div id="show-list"></div>
</body>
</html>
Problem appears to be that you can't treat append as if it was a text editor and you are writing html.
Anything that gets inserted needs to be a proper element ... not a start tag, then some text...then a close tag.
We can however modify your code slightly to produce html strings and then add that at the end
$.getJSON("data.json", function(data){
var json = data;
var html="<table class='specialists'>")
for(var i = 0; i < json.length; i++) {
var obj = json[i],
tableFormat = "</td><td>";
html+= "<tr><td class=1>" +
obj.FIELD1 + tableFormat +
obj.FIELD2 + tableFormat +
obj.FIELD3 + tableFormat +
obj.FIELD4 + tableFormat +
obj.FIELD5 + tableFormat +
obj.FIELD6 + tableFormat +
obj.FIELD7 + tableFormat +
obj.FIELD8 + "</td></tr>";
}
html+= '</table>';
$("#show-list").html(html);
//end getJSON inner function
});

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