The task is to fill the table with data from arrays id, name and price.
What am I doing wrong?
var data = {"id":["1986","1990","1989","1985","1988","1987"],"name":["name1","name2 ","name3 ","name4","латунь матовая ","name5"],"price":[1148,1396,2775,1270,1396,1270]};
var i = 0;
var table = '<table class="mainTable"><tr><th>id</th><th>name</th><th>price</th></tr>';
$.each(data, function(index, value){
table += ('<tr>');
table += ('<td>' + value.id + '</td>');
table += ('<td><img src="' + value.name + '"></td>');
table += ('<td>' + value.price + '</td>');
table += ('</tr>');
});
table += '</table>';
$('#tableContainer').html(table);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="tableContainer">
</div>
It doesn't work, because your input data is not organised as an array of objects, but as an object of arrays (which is less OOP).
As I prefer the array of objects as data structure, I would suggest to (temporarily) convert to that structure, and then your loop will work as expected:
var data = {"id":["1986","1990","1989","1985","1988","1987"],"name":["name1","name2 ","name3 ","name4","латунь матовая ","name5"],"price":[1148,1396,2775,1270,1396,1270]};
var array = data.id.map((id, i) => ({ id, name: data.name[i], price: data.price[i] }));
var i = 0;
var table = '<table class="mainTable"><tr><th>id</th><th>name</th><th>price</th></tr>';
$.each(array, function(index, value){
table += ('<tr>');
table += ('<td>' + value.id + '</td>');
table += ('<td><img src="' + value.name + '"></td>');
table += ('<td>' + value.price + '</td>');
table += ('</tr>');
});
table += '</table>';
$('#tableContainer').html(table);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="tableContainer">
</div>
As an unrelated remark, I would suggest using jQuery more in the process of building the table. This will also avoid problems you might get when your data has < or & characters in it immediately followed by letters, as that would be interpreted as HTML:
var data = {"id":["1986","1990","1989","1985","1988","1987"],"name":["name1","name2 ","name3 ","name4","латунь матовая ","name5"],"price":[1148,1396,2775,1270,1396,1270]};
var array = data.id.map((id, i) => ({ id, name: data.name[i], price: data.price[i] }));
var i = 0;
$('#tableContainer').empty().append($("<table>").addClass("mainTable").append(
$("<tr>").append(
$("<th>").text("id"),
$("<th>").text("name"),
$("<th>").text("price")
),
...array.map(value =>
$("<tr>").append(
$("<td>").text(value.id),
$("<td>").append($("<img>", { src: value.name })),
$("<td>").text(value.price)
)
)
));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="tableContainer">
</div>
Your data structure is not iterable. So you need to either change your data structure to be a list [{id: '1111', name: 'name1', price: 1111}], or you need to assume that all lists (id, name, price) are the same length, and use that length for the iteration.
As other answers detail how to use an iterable data structure, I'll handle the other method, where your data is already in this format, and won't change.
For this method, find the length of one property (id, name or price), and iterate through all of them using the index. Here is an example.
var data = {"id":["1986","1990","1989","1985","1988","1987"],"name":["name1","name2 ","name3 ","name4","латунь матовая ","name5"],"price":[1148,1396,2775,1270,1396,1270]};
var i = 0;
var table = '<table class="mainTable"><tr><th>id</th><th>name</th><th>price</th></tr>';
data.id.forEach((value, index) => {
table += ('<tr>');
table += ('<td>' + data.id[index] + '</td>');
table += ('<td><img src="' + data.name[index] + '"></td>');
table += ('<td>' + data.price[index] + '</td>');
table += ('</tr>');
});
table += '</table>';
$('#tableContainer').html(table);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="tableContainer">
</div>
You're processing the data as if it were structured as a single array, like this:
data = [
{
id: 1986,
name: "name1",
price: 1148
}
]
However, your data contains three arrays, not one:
data = {
id: [...],
name: [...],
price: [...],
}
If the data was structured like the first example, then value would contain an object for each array element, with the properties id, name and price available.
An option is to convert the first data structure to the second:
var data = {"id":["1986","1990","1989","1985","1988","1987"],"name":["name1","name2 ","name3 ","name4","латунь матовая ","name5"],"price":[1148,1396,2775,1270,1396,1270]};
var mappedData = data.id.map((id, index) => ({
id: id,
name: data.name[index],
price: data.price[index]
}))
Then, use the mappedData and access the properties as you're already doing, as follows:
var data = {"id":["1986","1990","1989","1985","1988","1987"],"name":["name1","name2 ","name3 ","name4","латунь матовая ","name5"],"price":[1148,1396,2775,1270,1396,1270]};
var mappedData = data.id.map((id, index) => ({
id: id,
name: data.name[index],
price: data.price[index]
}))
var i = 0;
var table = '<table class="mainTable"><tr><th>id</th><th>name</th><th>price</th></tr>';
$.each(dataMapped, function(index, value){
table += ('<tr>');
table += ('<td>' + value.id + '</td>');
table += ('<td><img src="' + value.name + '"></td>');
table += ('<td>' + value.price + '</td>');
table += ('</tr>');
});
table += '</table>';
$('#tableContainer').html(table);
var data = {"id":["1986","1990","1989","1985","1988","1987"],"name":["name1","name2 ","name3 ","name4","латунь матовая ","name5"],"price":[1148,1396,2775,1270,1396,1270]};
var i = 0;
var table = '<table class="mainTable"><tr><th>id</th><th>name</th><th>price</th></tr>';
$.each(data["id"], function(index, value){
table += ('<tr>');
table += ('<td>' + value + '</td>');
table += ('<td><img src="' + data["name"][index] + '"></td>');
table += ('<td>' + data["price"][index] + '</td>');
table += ('</tr>');
});
table += '</table>';
$('#tableContainer').html(table);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="tableContainer">
</div>
There ways to iterate the data as you defined it but I think it's better to define it in a proper way, as an array of entities ($.each is to iterate through an array):
[
{
"id": "1986",
"name": "name1",
"price": 1148
},
{
"id": "1990",
"name": "name2",
"price": 1396
},
];
Without changing the input you can do this.
var data = {
"id": ["1986", "1990", "1989", "1985", "1988", "1987"],
"name": ["name1", "name2 ", "name3 ", "name4", "латунь матовая ", "name5"],
"price": [1148, 1396, 2775, 1270, 1396, 1270]
};
document.getElementById("tableContainer").innerHTML = data.id
.map((id,i) => `<tr><td>${id}</td>
<td><img src="${data.name[i]}"></td>
<td>${data.price[i]}</td></tr>`).join("")
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<table class="mainTable">
<thead>
<tr>
<th>id</th>
<th>name</th>
<th>price</th>
</tr>
</thead>
<tbody id="tableContainer"></tbody>
</table>
</div>
I also recommmend you change the input to an array of objects. It makes the parsing simpler
var data = [
{ "id": "1986", "name": "name1", "price": 1148},
{ "id":"1990", "name": "name2", "price": 1396},
{ "id":"1989", "name": "name3", "price": 2775},
{ "id":"1985", "name": "name4", "price": 1270},
{ "id":"1988", "name": "латунь матовая ", "price": 1396},
{ "id":"1987", "name": "name5", "price": 1270}
];
document.getElementById("tableContainer").innerHTML = data
.map(({id,name,price}) => `<tr><td>${id}</td>
<td><img src="${name}"></td>
<td>${price}</td></tr>`).join("")
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<table class="mainTable">
<thead>
<tr>
<th>id</th>
<th>name</th>
<th>price</th>
</tr>
</thead>
<tbody id="tableContainer"></tbody>
</table>
</div>
Related
In this I am trying to sort the data by partNo and it is perfectly sorted with this, but my problem is that the first column of the table does not sort with the rest of the columns. sr No has to be sorted with all other columns
here sr No is a key which is not sorted with other columns
let productDetails = {
"10": [{
id: "1",
partNo: "100",
productName: "bag",
size: "30",
color: ["Blue"],
description: "sky bags ",
}],
"20": [{
id: "2",
partNo: "15",
productName: "bottle",
size: "10",
color: ["Green", "Orange"],
description: "plastic and still",
}]
,
"30": [{
id: "4",
partNo: "25",
productName: "lunchbox",
size: "20",
color: ["Blue", "Red"],
description: "fresh food",
}],
"40": [{
id: "3",
partNo: "45",
productName: "pen",
size: "10",
color: ["Red", "Blue"],
description: "gel pen ",
}]
};
/**
* This function displays the data in the table
*/
function displayData() {
objectArray = Object.values(productDetails);
display(objectArray);
}
function display(productStore) {
messageTable(" ");
let table = "<table border = 1 cellpadding = 10 ><th colspan=7 >Product Details</th><tr><th>sr No</th><th>Product Id</th><th>Part No</th><th>Name</th><th>Size</th><th>Color</th><th>Description</th></tr>";
for (var key in productDetails) {
for (var weight in productDetails[key]) {
table += "<tr><td>" + key + "</td>";
table += "<td>" + productDetails[key][weight].id + "</td>";
table += "<td>" + productDetails[key][weight].partNo + "</td>";
table += "<td>" + productDetails[key][weight].productName + "</td>";
table += "<td>" + productDetails[key][weight].size + "</td>";
table += "<td>" + productDetails[key][weight].color + "</td>";
table += "<td>" + productDetails[key][weight].description + "</td>";
}
} messageTable(table);
}
/**
* function to sort an array by part No
*/
function sortByPartNo() {
let arr = [];
item = Object.keys(productDetails)
console.log(item)
item.forEach(function (index) {
productDetails[index].forEach(function (indexA) {
arr.push(indexA);
});
})
arr.sort(function (first, second) {
return parseFloat(first.partNo) - parseFloat(second.partNo);
});
console.log(arr)
printArray(arr, item)
}
/**
* function to print array in the table
*/
function printArray(arr, item) {
messageTable(" ");
let table = "<table border = 1 cellpadding = 10 ><th colspan=7 >Product Details</th><tr><th>sr No</th><th>Product Id</th><th>Part No</th><th>Name</th><th>Size</th><th>Color</th><th>Description</th></tr>";
for (let key in arr) {
table += "<tr><td>" + item[key] + "</td>";
table += "<td>" + arr[key].id + "</td>";
table += "<td>" + arr[key].partNo + "</td>";
table += "<td>" + arr[key].productName + "</td>";
table += "<td>" + arr[key].size + "</td>";
table += "<td>" + arr[key].color + "</td>";
table += "<td>" + arr[key].description + "</td>";
} messageTable(table);
}
/**
* function is to print the table
*/
function messageTable(data) {
document.getElementById("messageTableA").innerHTML = data;
}
/**
* this function is to print the message
*/
function message(message) {
document.getElementById("demo").innerHTML = message;
}
<!DOCTYPE html>
<html>
<head>
<style>
th,
td,
p,
input {
font-family: Arial, Helvetica, sans-serif;
}
table,
th,
td {
border: solid 1px #DDD;
border-collapse: collapse;
padding: 10px 10px;
text-align: center;
}
th {
font-weight: bold;
}
</style>
</head>
<body onload="displayData()">
<h2>Product Details:</h2>
<form action="">
<input type="button" value="sortByPartNo" onclick="sortByPartNo();">
<p id="result"></p>
<p id="demo"></p>
<p id="messageTableA"></p>
</form>
</body>
</html>
There's a couple ways to go about this, but the simplest would be to just construct a new objects from the original one that contains both the keys and values.
i.e. turn this:
{
"10": [{
"partNo": "100",
"size": "30",
// etc
}],
// ...
}
into this
[
{
"key": "10",
"partNo": "100",
"size": "30",
// etc
},
// ...
]
or alternatively, something like this works too. A similar approach is used in the concrete code example below.
[
{
"key": "10",
"value": {
"partNo": "100",
"size": "30",
// etc
},
},
// ...
]
Basically, we just need to bundle all the related information together before we do a sort(). After we sort, we can pass the bundled data as-is to your display functions, or we can separate them back into two lists, however you prefer.
A practical simplified example:
const data = {
1: {
color: 'blue',
size: 10,
},
2: {
color: 'green',
size: 50,
},
3: {
color: 'yellow',
size: 5,
},
}
// Object.entries() will reshape the data in a way that keeps keys and values together
// then we .sort() based on size
const sorted = (
Object.entries(data)
.sort((x, y) => x[1].size - y[1].size)
)
console.log('sorted keys and values', sorted)
// If you want, you can then split them back out into two separate array, like you had it:
console.log('sorted keys', sorted.map(x => x[0]))
console.log('sorted values', sorted.map(x => x[1]))
See this to learn about Object.entries, used in this particular example.
Scotty Jamison responded first and gave you a good description of options and alternatives. I urge you to accept his answer.
However, I figured I minus well provide my work that I had developed in response to your original question incorrectly marked as a duplicate (as you mention in the comments to your question here). It is a more fully worked out version of Scotty's first proposal, which places the outer key as a property inside the array entry.
// Just a convenience for building productDetails
let pdVal = (id,no,name,size,colors,desc) => ({
id: id,
partNo: no,
productName: name,
size: size,
color: colors,
description: desc
})
let productDetails = {
"10": [pdVal("1","100","bag","30",["Blue"],"sky bags ")],
"20": [pdVal("2","15","bottle","10",["Green", "Orange"],"plastic and still")],
"30": [pdVal("4","25","lunchbox","20",["Blue", "Red"],"fresh food")],
"40": [pdVal("3","45","pen","10",["Red", "Blue"],"gel pen ")]
};
function sortByPartNo() {
let arr = [];
for (let key of Object.keys(productDetails)) {
let obj = productDetails[key][0];
arr.push(Object.assign({}, obj, {key}));
}
arr.sort((a,b) => parseFloat(a.partNo) - parseFloat(b.partNo))
printArray(arr);
}
function printArray(arr) {
messageTable(" ");
let table = `
<table border = 1 cellpadding = 10 >
<th colspan=7 >Product Details</th>
<tr>
<th>sr No</th>
<th>Product Id</th>
<th>Part No</th>
<th>Name</th>
<th>Size</th>
<th>Color</th>
<th>Description</th>
</tr>
`;
for (let item of arr) {
console.log({arr})
table += "<tr><td>" + item.key + "</td>";
table += "<td>" + item.id + "</td>";
table += "<td>" + item.partNo + "</td>";
table += "<td>" + item.productName + "</td>";
table += "<td>" + item.size + "</td>";
table += "<td>" + item.color + "</td>";
table += "<td>" + item.description + "</td>";
}
messageTable(table);
}
function messageTable(data) {
document.getElementById("messageTableA").innerHTML = data;
}
<input type="button" value="sortByPartNo" onclick="sortByPartNo();">
<p id="result"></p>
<p id="demo"></p>
<p id="messageTableA"></p>
javascript code
$(function(){
$(".user").on("click",function(e){
e.preventDefault();
var email = $(this).data("email");
$.ajax({
data:{email:email},
type: "POST",
url: 'getUser_detail.php',
success: function(data) {
var data = JSON.parse(data);
for (var i = 0; i < data['basic'].length; i++) {
$('#inputs').append('<label>Email:</label><input type="text" readonly class="form-control-plaintext" value="' + data['basic'][i].email + '" name="email[]" size="15">');
$('#inputs').append('<label>Password:</label><input type="text" readonly class="form-control-plaintext" value="'+ data['basic'][i].Pass +'" name="pass[]" size="5">');
$('#inputs').append('<label>Status:</label><input type="text" readonly class="form-control-plaintext" value="'+ data['basic'][i].status +'" name="pass[]" size="5">');
$('#inputs').append('<label>Acc. Address:</label><input type="text" readonly class="form-control-plaintext" value="'+ data['basic'][i].Accno +'" name="pass[]" size="44">');
$('#inputs').append('<label>Balance:</label><input type="text" readonly class="form-control-plaintext" value="'+ data['basic'][i].bal +'" name="pass[]" size="10">');
}
for( var j = 0; j<data['detail'].length; j++) {
var List = ["<tr><td>" + data['detail'][i].type + "</td><td>"+data['detail'][i].DB+"</td><td>"+data['detail'][i].LD+"</td><td>"+data['detail'][i].Prof+"</td><td>"+data['detail'][i].Server_stat+"</td></tr>"];
}
$("#bodywallet").append(List);
},
});
});
})
html code
<table class="table" id="wallet">
<thead class=" text-primary">
<tr>
<th class="text-left">Type</th>
<th class="text-left">Date_Bought</th>
<th class="text-left">Expires</th>
<th class="text-left">Profit</th>
<th class="text-left">Status</th>
</tr>
</thead>
<tbody class="text-left" id="bodywallet" >
</tbody>
</table>
this is what my data should be display on table
but it is displaying the first record only
i have checked json is bringing all the required data. what i have done wrong what is the mistake.any help will be appreciated. thanks
php code
while($row2 = mysqli_fetch_array($alEmailrslt))
{
$json_array['detail'][] = $row2;
}
echo json_encode($json_array);
You are putting everything in an array I and appending it every round.
You should use something like this instead:
success: function (data) {
var data = JSON.parse(data);
var list = []; // only one array
for (var j = 0; j < data['detail'].length; j++) {
// push to this array instead of overwriting the variable
list.push("<tr><td>" + data['detail'][j].type + "</td><td>" + data['detail'][j].DB + "</td><td>" + data['detail'][j].LD + "</td><td>" + data['detail'][j].Prof + "</td><td>" + data['detail'][j].Server_stat + "</td></tr>");
}
// update html once
// the join "glues" all parts of the array into one string
$("#bodywallet").append(list.join());
}
I think your list is not getting updated every time and the simplest approach would be, please find below code snippet:
$(document).ready(function() {
this.json = {
"Students": [{
"id": "1",
"hometown": "London",
"gender": "Male",
"GPA": "8",
"name": "Lee",
},
{
"id": "2",
"hometown": "NY",
"gender": "Male",
"GPA": "9",
"name": "Shaldon",
}, {
"id": "3",
"hometown": "Paris",
"gender": "Female",
"GPA": "7",
"name": "Julie",
}
]
};
this.renderTable = function(Students) {
var tbody = document.getElementById('tbody');
tbody.innerHTML = "";
for (var i = 0; i < Students.length; i++) {
var tr = "<tr>";
tr += "<td>ID</td>" + "<td>" + Students[i].id + "</td></tr>";
tr += "<td>HomeTown</td>" + "<td>" + Students[i].hometown + "</td></tr>";
tr += "<td>Gender</td>" + "<td>" + Students[i].gender + "</td></tr>";
tr += "<td>GPA</td>" + "<td>" + Students[i].GPA + "</td></tr>";
tr += "<td>NAME</td>" + "<td>" + Students[i].name + "</td></tr>";
tr += "<hr>";
tbody.innerHTML += tr;
}
}
this.renderTable(this.json.Students);
console.log(this.json.Students);
//code for filtering//
this.Filter = function() {
var search = document.getElementById('search');
var category = document.getElementById('category');
var filteredObj = this.json.Students;
filteredObj = $.map(this.json.Students, function(val, key) {
if (search.value === val[category.value]) return val;
});
filteredObj.length>0 ? this.renderTable(filteredObj) : this.renderTable(this.json.Students);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<p></p>
<input id="search" type="search">
<select id = "category">
<option value = "select">select</option>
<option value = "id">ID</option>
<option value = "hometown">HomeTown</option>
<option value = "gender">Gender</option>
<option value = "GPA">GPA</option>
<option value = "name">NAME</option>
</select>
<button onclick="Filter()">Filter</button>
<table>
<tbody id="tbody"></tbody>
</table>
I am trying to use ngx-clipboard module in my angular application.
The data in the table is coming from a service and i am using jsonToTable() to insert a dynamic table.
component.ts
generateOverrideCode(){
try {
document.getElementById('tableGoesHere').innerHTML = this.jsonToTable(data, 'table table-sm table-dark');
}
catch (ex) {
console.log('--generate override code', ex);
}
}
capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
jsonToTable(json, classes){
var cols = Object.keys(json[0]);
var headerRow = '';
var bodyRows = '';
classes = classes || '';
cols.map((col)=>{
headerRow += '<th>' + this.capitalizeFirstLetter(col) + '</th>';
});
json.map((row)=> {
bodyRows += '<tr>';
cols.map((colName)=> {
if(colName != 'population')
bodyRows += '<td>' + row[colName] + '</td>';
else
bodyRows += '<td id="colName+row">' + row[colName] + '<button></button>' + '</td>'; //I want to add a dynamic id to the button added to each cell of this row, so that i can use the id to target the text of that cell.
});
bodyRows += '</tr>';
});
return '<table class="' +
classes +
'"><thead><tr>' +
headerRow +
'</tr></thead><tbody>' +
bodyRows +
'</tbody></table>';
}
}
var data = [
{ country: 'China', population: 1379510000 },
{ country: 'India', population: 1330780000 },
{ country: 'United States', population: 324788000 },
{ country: 'Indonesia', population: 260581000 },
{ country: 'Brazil', population: 206855000 },
];
component.html
<div class="row">
<div class="col-sm-12">
<button (click)="generateOverrideCode()">Generate</button>
</div>
</div>
<div id="tableGoesHere"></div>
What i am trying to achieve is adding a copy button next to the each cell in the third column.
I also want each cell to have a unique id so i can target it using ngx-clipboard directive. Follow link for example
https://maxisam.github.io/ngx-clipboard/
I have created a stackblitz example as well.
https://stackblitz.com/edit/angular-s5g1b5
Please help me with adding unique id to each cell then i will move to adding ngx-clipboard.(i have added comments in stackblitz where i attempted to add unique id)
I'm having an issue while displaying json data in an html table. I believe it has to do with the fact that my json's formatted really strange (i can't change it)
Thanks in advance.
{"name":["instance-5","instance-6"],"id"["1178823664323071067","5394281241544297728"],"ip":["35.189.8.115","35.201.16.102"],"status":["RUNNING","RUNNING"]}
<script>
$( document ).ready(function() {
$.ajax({
url: '/api/instance/list',
type: 'get',
dataType: 'json',
error: function(data){
},
success: function(data){
var tr = $('<tr>');
tr.append('<td>' + data.name + '<td>');
tr.append('<td>' + data.id + '<td>');
tr.append('<td>' + data.ip + '<td>');
tr.append('<td>' + data.status + '<td>');
$('#application-table').append(tr);
}
});
});
</script>
<table id="application-table" class="aui">
<thead>
<tr>
<th width="20%">Instance Name</th>
<th width="20%">ID</th>
<th width="20%">IP</th>
<th width="5%">Status</th>
</tr>
</thead>
Your response is formatted such that each property is its own array, presumably meaning that name[0] is related to all the other [0] indexed items in the other arrays.
Therefore to achieve what you require you can loop over the response and put all the values within the properties at the same index within the new row, like this:
var data = {
"name": ["instance-5", "instance-6"],
"id": ["1178823664323071067", "5394281241544297728"],
"ip": ["35.189.8.115", "35.201.16.102"],
"status": ["RUNNING", "RUNNING"]
}
for (var i = 0; i < data.name.length; i++) {
var tr = $('<tr>');
tr.append('<td>' + data.name[i] + '<td>');
tr.append('<td>' + data.id[i] + '<td>');
tr.append('<td>' + data.ip[i] + '<td>');
tr.append('<td>' + data.status[i] + '<td>');
$('#application-table').append(tr);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="application-table"></table>
That said, I'd recommend finding a way to change your response structure to relate row data in each item of a single array, something like this:
var data = [{
"name": "instance-5",
"id": "1178823664323071067",
"ip": "35.189.8.115",
"status": "RUNNING"
}, {
"name": "instance-6",
"id": "1178823664323071067",
"ip": "35.201.16.102",
"status": "RUNNING"
}]
var html = data.map(function(row) {
return `<tr><td>${row.name}</td><td>${row.id}</td><td>${row.ip}</td><td>${row.status}</td></tr>`;
});
$('#application-table').append(html.join(''));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="application-table"></table>
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);