key is not sorted in JSON array using javascript - javascript

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>

Related

I want to make HTML table from array

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>

after refresh the page and add new data so newly added data is replaced with old data in the table [javascript]

here I'm working with localstorage in javascript
here is my code for enter productDetails in the table using a form. when i'm enter productDetails in the table and refresh the page the entered data is in the table because of localStorage. but my problem is that when I refresh the page and again add new data so that newly added data is replaced with data which is added before refresh the page. and I want all my data instead of replacing
let productDetails = {
};
/**
* this function is for get the value from form
*/
function getValue() {
let id = document.getElementById('productId').value;
let partNo = document.getElementById('productNo').value;
let productName = document.getElementById('productName').value;
let size = getRadioValue();
let color = getCheckBoxValue();
let description = document.getElementById('description').value;
let date = document.getElementById('date').value;
let address = document.getElementById('address').value;
let companyName = document.getElementById('companyName').value;
return {
id, partNo, productName, size, color, description, date, address, companyName
};
}
/**
* function to insert data into table
*/
function insertion() {
let value = getValue();
let letter = value.productName[0];
if (!productDetails.hasOwnProperty(letter)) {
productDetails[letter] = [];
}
let object = {
weight: value.weight, id: value.id, partNo: value.partNo, productName: value.productName, size: value.size, color: value.color, description: value.description,
companyDetails: {
date: value.date,
address: value.address,
companyName: value.companyName
}
};
JSON.parse(window.localStorage.getItem('productDetails'));
productDetails[letter].push(object);
localStorage.setItem("productDetails", JSON.stringify(productDetails));
displayData();
message("");
}
/**
* this function display the data in table
*/
function displayData() {
objectArray = Object.values(productDetails);
display(objectArray);
}
/**
* function to display table
*/
function display() {
var result = JSON.parse(window.localStorage.getItem("productDetails"));
console.log(result)
messageTable(" ");
let table = "<table border = 1 cellpadding = 10 ><th colspan=7 >Product Details</th><th colspan=7 >company Details</th><tr><th>weight</th><th>Product Id</th><th>Part No</th><th>Name</th><th>Size</th><th>Color</th><th>Description</th><th>Date</th><th>Address</th><th>Company name</th></tr>";
for (var key in result) {
for (var weight in result[key]) {
//let companyDetails = result[key][weight].companyDetails ? result[key][weight].companyDetails : { date: "", address: "", companyName: "" };
table += "<tr><td>" + key + "</td>";
table += "<td>" + result[key][weight].id + "</td>";
table += "<td>" + result[key][weight].partNo + "</td>";
table += "<td>" + result[key][weight].productName + "</td>";
table += "<td>" + result[key][weight].size + "</td>";
table += "<td>" + result[key][weight].color + "</td>";
table += "<td>" + result[key][weight].description + "</td>";
table += "<td>" + result[key][weight].companyDetails.date + "</td>";
table += "<td>" + result[key][weight].companyDetails.address + "</td>";
table += "<td>" + result[key][weight].companyDetails.companyName + "</td>";
}
} messageTable(table);
console.log(result)
}
What you need to do is add a check looking for the localstorage key for your data when the page loads, if the check is true then add the previous localstorage data to your productDetails object. This is the Example =>
window.onload = init;
var arr = [];
function init() {
if(localStorage.getItem("productDetails")) {
arr.push(JSON.parse(localStorage.getItem("productDetails")));
getValue(); /*Then Continue eg.Refer to a function*/
}
else {
getValue(); /*Do something eg.Refer to a function*/
}
}
The concept is when the page loads add a window.onload function to check whether the localStorage key "productDetails" exists. If the key exist then add/push the value stored by the key to the array arr in this example. If it does not exist then eg. Do something like => Refer to a function.

populate json data in tables

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>

Need to add copy button to each cell of a column in html

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)

ajax response can not be displayed

This is my javascript function that pull the data from the following link
function jsonCall1() {
$.post("http://tallentex.com/phpwebservices/feedbackapp/index.php/hostel_service/syncData", { id: 0 }, function (data) {
var tbl=$("<table/>").attr("id","mytable");
$("#dv").append(tbl);
for (var i = 0; i < data.length; i++) {
var tr = "<tr>";
var td1 = "<td>" + data[i]["id"] + "</td>";
var td2 = "<td>" + data[i]["fno"] + "</td>";
var td3 = "<td>" + data[i]["attn_no"] + "</td></tr>";
$("#mytable").append(tr + td1 + td2 + td3);
}
console.log(data);
});
}
This is the output of this function in console.I want to display this output in html table and also want to send to server using datatable
In this response I want to display array data in html table and also want to send this array data to server
{status: 1, data: Array(4)}
data:Array(4)
0:{id: "1", fno: "16078134", hostel_id: "12345", attn_no: "0010146998", create_date: "2017-08-21 10:31:02"}
1:{id: "2", fno: "16078134", hostel_id: "12345", attn_no: "0010146998", create_date: "2017-08-21 10:31:02"}
2:{id: "3", fno: "16078134", hostel_id: "12345", attn_no: "0010146998", create_date: "2017-08-21 10:31:02"}
3:{id: "4", fno: "16078134", hostel_id: "12345", attn_no: "0010146998", create_date: "2017-08-21 10:31:02"
function jsonCall1() {
$.post("http://tallentex.com/phpwebservices/feedbackapp/index.php/hostel_service/syncData", { id: 0 }, function (data) {
var tbl=$("<table/>").attr("id","mytable");
$("#dv").append(tbl);
for (var i = 0; i < data.length; i++) {
var str = `<tr>
<td>${data[i].id}</td>
<td>${data[i].fno}</td>
<td>${data[i].attn_no}</td>
</tr>`;
$("#mytable").append(str);
}
console.log(data);
});
}

Categories

Resources