json results only showing one thing in table - html

I am havign an issue where there is only one item being shown in my table (usually the most recent bug entered)
could you let me know if there is an error with my code?
Here is it
//Web service call to get the data
var getAllBugsData = $.get("https://m2052626.scm.tees.ac.uk/AST_14/Bugg.ly2/index.php/bug/GetAllBugs",
function(data)
{
var j = 0;
var myTotal = data.length ;
for(var i =0; i < data.length;i++)
{
var item = data[i];
bug_id = item.bug_id;
BugType = item.BugType;
Bugaddress = item.Bugaddress;
admin_id = item.admin_id;
status = item.status;
Description = item.description;
type = item.type;
var bugDetails = '<div class="PropDetails">Bug Id: '+bug_id+'</div><div class="PropDetails">Type of Bug: '+BugType+'</div><div class="PropDetails">Admin Number :'+admin_id+'</div><div class="PropDetails">Type Of Bug: '+type+'</div>';
$('.listAllBugs').append('<tr class="table-stroke"><td>'+bugDetails+'</td><td>Edit</tr>');
And the table code is this
<!--Data Table Goes HERE-->
<table data-role="table" data-mode="reflow" class="ui-responsive table-stroke">
<thead>
<tr>
<th width="100%">Bug Details</th>
</tr>
</thead>
<tbody class="listAllBugs">
</tbody>
</table>

Related

How to export paginated table data in CSV?

I have a problem exporting the paginated table in csv file. It cannot export the whole paginated table, just only export the first paginated table data.
Below is my coding:
HTML
<button onclick="exportTableToCSV('manufacturer_brand.csv')">Export</button>
<table id="table_js" class="table table-bordered table-striped">
<thead>
<tr>
<th style="width: 10%;">Action</th>
<th style="width: 5%;">No.</th>
<th style="">Brand Name</th>
</thead>
<tfoot>
<tr>
<th style="width: 10%;">Action</th>
<th style="width: 5%;">No.</th>
<th style="">Brand Name</th>
</tr>
</tfoot>
</table>
Javascript
function downloadCSV(csv, filename) {
var csvFile;
var downloadLink;
// CSV file
csvFile = new Blob([csv], {type: "text/csv"});
// Download link
downloadLink = document.createElement("a");
// File name
downloadLink.download = filename;
// Create a link to the file
downloadLink.href = window.URL.createObjectURL(csvFile);
// Hide download link
downloadLink.style.display = "none";
// Add the link to DOM
document.body.appendChild(downloadLink);
// Click download link
downloadLink.click();
}
function exportTableToCSV(filename) {
var csv = [];
var rows = document.querySelectorAll("table tr");
for (var i = 1; i < rows.length; i++) {
var row = [], cols = rows[i].querySelectorAll("td, th");
for (var j = 1; j < cols.length; j++)
row.push(cols[j].innerText);
csv.push(row.join(","));
}
// Download CSV file
downloadCSV(csv.join("\n"), filename);
}
Export CSV file result like below, just can export first paginated page table, other paginate cannot export:
Below is my table, actually I have a total of 7 paginated pages in the table
How someone can guide me on how to export paginate table in a CSV file.

How to put elements of an array into html table rows and columns

I need to put each element of an array into the corresponding table column, but currently it just puts the entire array into the first column. I feel like this solution will be a simple nested for loop but I am unsure, would appreciate any help. Thanks!
index.html
<div id="PersonContainer" class="DBcontainer">
<form action='/addPerson' method="GET"></form>
<table class="center" id="personTable">
<caption>People Table</caption>
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Hooks ID</th>
<th>Soft Plastic ID</th>
<th>Rods ID</th>
<th>Number of Hooks</th>
<th>Number of Soft Plastics</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<button type="button" onclick="displayPerson()">Click Me</button>
</form>
</div>
index.html script
<script>
function displayPerson() {
// console.log('test');
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var person = xhttp.responseText;
var element = document.getElementById("personTable");
var result = JSON.parse(person).map((item) => Object.values(item));
for(i = 0; i < result.length; i++){
element.innerHTML += '<td>' + result[i] + '</td>';
}
}
};
xhttp.open("GET", "/AddPerson", true);
xhttp.send();
}
</script>
the xhttp.responseText
[{"id":1,"first_name":"Tyler","last_name":"Marlow","hooks_id":1,"sp_id":1,"rods_id":1,"num_hooks":10,"num_sp":30},{"id":2,"first_name":"Jon","last_name":"Marlow","hooks_id":2,"sp_id":1,"rods_id":1,"num_hooks":50,"num_sp":200}]
Also note that when another person is added I would like another row to be added to the table with the values in proper columns
Putting a new row onto a table in JavaScript can be done with the insertRow function and adding a cell to a row can be done with the insertCell function.
So in your code (depending on exactly what your parsed JSON looks like) in your for loop you are going to do something like:
row = element.insertRow(i); // add a new row to your table
row.insertCell(0).innerHTML =
row.insertCell(1).innerHTML =
and so on
....
But of course you'd put the insertCell line into a for loop as well.
function displayPerson() {
// console.log('test');
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var person = xhttp.responseText;
var element = document.getElementById("personTable");
var rows = ``;
JSON.parse(person).forEach(item => {
var row = `<tr>`;
row += `<td>${item.first_name}</td>`;
row += `<td>${item.last_name}</td>`;
row += `<td>${item.hooks_id}</td>`;
row += `<td>${item.sp_id}</td>`;
row += `<td>${item.rods_id}</td>`;
row += `<td>${item.num_hooks}</td>`;
row += `<td>${item.num_sp}</td>`;
row += `</tr>`;
rows += row;
});
element.innerHTML = rows;
}
};
xhttp.open("GET", "/AddPerson", true);
xhttp.send();
}
<div id="PersonContainer" class="DBcontainer">
<form action='/addPerson' method="GET">
<table class="center">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Hooks ID</th>
<th>Soft Plastic ID</th>
<th>Rods ID</th>
<th>Number of Hooks</th>
<th>Number of Soft Plastics</th>
</tr>
<thead>
<tbody id="personTable">
</tbody>
</table>
<button type="button" onclick="displayPerson()">Click Me</button>
</form>
</div>

How to export multiple HTML tables into a single excel file, along with the html table's css/style?

I know there are a lot of this type of question in this site, but i cant find any working solution for this that suit my need. What i need is
1. export multiple html table to excel
2. the table in the excel look exactly like the html table (the css, styling are the same. e.g background-color)
Is there any way to do this using javascript,etc.?
I found one question for this problem here, but the solution shown there did not solve the css problem. Means that the excel table not have the css like the html table (e.g The excel table doesnt have yellow background eventhough the html table have it)
So basically the main problem is I need the format for the excel file to be same as the html table (css,etc.). Sorry I am new to programming..
Here you can access the jsfiddle. Or if the link doesnt work, you can just try it below (The codes are taken from the original post , but with an addition of a simple yellow-colored background css in it's tr)Thanks in advance.
var tablesToExcel = (function() {
var uri = 'data:application/vnd.ms-excel;base64,'
, tmplWorkbookXML = '<?xml version="1.0"?><?mso-application progid="Excel.Sheet"?><Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet">'
+ '<DocumentProperties xmlns="urn:schemas-microsoft-com:office:office"><Author>Axel Richter</Author><Created>{created}</Created></DocumentProperties>'
+ '<Styles>'
+ '<Style ss:ID="Currency"><NumberFormat ss:Format="Currency"></NumberFormat></Style>'
+ '<Style ss:ID="Date"><NumberFormat ss:Format="Medium Date"></NumberFormat></Style>'
+ '</Styles>'
+ '{worksheets}</Workbook>'
, tmplWorksheetXML = '<Worksheet ss:Name="{nameWS}"><Table>{rows}</Table></Worksheet>'
, tmplCellXML = '<Cell{attributeStyleID}{attributeFormula}><Data ss:Type="{nameType}">{data}</Data></Cell>'
, base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) }
, format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) }
return function(tables, wsnames, wbname, appname) {
var ctx = "";
var workbookXML = "";
var worksheetsXML = "";
var rowsXML = "";
for (var i = 0; i < tables.length; i++) {
if (!tables[i].nodeType) tables[i] = document.getElementById(tables[i]);
for (var j = 0; j < tables[i].rows.length; j++) {
rowsXML += '<Row>'
for (var k = 0; k < tables[i].rows[j].cells.length; k++) {
var dataType = tables[i].rows[j].cells[k].getAttribute("data-type");
var dataStyle = tables[i].rows[j].cells[k].getAttribute("data-style");
var dataValue = tables[i].rows[j].cells[k].getAttribute("data-value");
dataValue = (dataValue)?dataValue:tables[i].rows[j].cells[k].innerHTML;
var dataFormula = tables[i].rows[j].cells[k].getAttribute("data-formula");
dataFormula = (dataFormula)?dataFormula:(appname=='Calc' && dataType=='DateTime')?dataValue:null;
ctx = { attributeStyleID: (dataStyle=='Currency' || dataStyle=='Date')?' ss:StyleID="'+dataStyle+'"':''
, nameType: (dataType=='Number' || dataType=='DateTime' || dataType=='Boolean' || dataType=='Error')?dataType:'String'
, data: (dataFormula)?'':dataValue
, attributeFormula: (dataFormula)?' ss:Formula="'+dataFormula+'"':''
};
rowsXML += format(tmplCellXML, ctx);
}
rowsXML += '</Row>'
}
ctx = {rows: rowsXML, nameWS: wsnames[i] || 'Sheet' + i};
worksheetsXML += format(tmplWorksheetXML, ctx);
rowsXML = "";
}
ctx = {created: (new Date()).getTime(), worksheets: worksheetsXML};
workbookXML = format(tmplWorkbookXML, ctx);
console.log(workbookXML);
var link = document.createElement("A");
link.href = uri + base64(workbookXML);
link.download = wbname || 'Workbook.xls';
link.target = '_blank';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
})();
<table id="tbl1" class="table2excel">
<tr style="background-color:yellow;">
<td>Product</td>
<td>Price</td>
<td>Available</td>
<td>Count</td>
</tr>
<tr>
<td>Bred</td>
<td>1
</td>
<td>2
</td>
<td>3
</td>
</tr>
<tr>
<td>Butter</td>
<td>4
</td>
<td>5
</td>
<td >6
</td>
</tr>
</table>
<hr>
<table id="tbl2" class="table2excel">
<tr>
<td>Product</td>
<td>Price</td>
<td>Available</td>
<td>Count</td>
</tr>
<tr>
<td>Bred</td>
<td>7
</td>
<td>8
</td>
<td>9
</td>
</tr>
<tr>
<td>Butter</td>
<td>14
</td>
<td>15
</td>
<td >16
</td>
</tr>
</table>
<button onclick="tablesToExcel(['tbl1','tbl2'], ['ProductDay1','ProductDay2'], 'TestBook.xls', 'Excel')">Export to Excel</button>
Found the solution for this. I use the DataTables. Read more here DataTables forum

Want to add Different colors to Different Dynamic ids in a table

I am having some issues on <tr> background color, having the same <tr id="">
Here is my Table.
<table class="table">
<tr id="2552">
<td>Roll No 1</td>
<td>800</td>
</tr>
<tr id="2552">
<td>Roll No 1</td>
<td>700</td>
</tr>
<tr id="4444">
<td>Roll No 11</td>
<td>800</td>
</tr>
<tr id="4444">
<td>Roll No 11</td>
<td>900</td>
</tr>
<tr id="7676">
<td>Roll No 12</td>
<td>800</td>
</tr>
<tr id="7676">
<td>Roll No 12</td>
<td>900</td>
</tr>
</table>
What I want.
Every 2 <tr> have same id But these ids are dynamic.
I want the <tr> having same id get different background-color.
Now in this table there are 3 ids are used. So 3 different colors can be there.
I have applied many jquery codes but failed.
Please help me
I Developed Dynamic table row id based color set and i hope its solve your problem. Code Reference
var table = document.getElementsByTagName("table")[0];
var secondRow = table.rows[1];
var count=0;
var trid =[];
var clr =[];
for(var i=0;i<table.rows.length;i++)
{
trid.push(table.rows[i].id);
}
var uniqueArray = [];
for(i=0; i < trid.length; i++){
if(uniqueArray.indexOf(trid[i]) === -1) {
uniqueArray.push(trid[i]);
}
}
for(var i = 0; i < uniqueArray.length; i++)
{
clr.push('#'+Math.floor(Math.random()*16777215).toString(16));
}
for (var i = 0; i < table.rows.length; i++) {
for(var j = 0; j < uniqueArray.length; j++)
{
if(table.rows[i].id ==uniqueArray[j]){
table.rows[i].style.backgroundColor = clr[j];
}
}
}
Hi Use looping in Jquery, loop through each tr and determine its ID, then apply bg color
$( "tr" ).each(function( index ) {
var ID = $(this)..attr('id');
if(ID == '2221')
{
$(this).css('background-color', 'red');
}
else if(ID == '2223')
{
$(this).css('background-color', 'blue');
}
});
How about something like this?
const used_ids = []
$( "tr" ).each(function( index ) {
const id = $(this).attr.('id')
if (!used_ids.includes(id)) {
// If the id has not been met before, add it to the array.
used_ids.push(id)
}
// Get index of id from array of used ids
const index = used_ids.indexOf(id)
// If index is an even number, set background colour to grey, otherwise white
if (index%2 === 0) $(this).css('background-color', 'white');
else $(this).css('background-color', 'grey');
})
It builds an array of unique ids, then assigns white to those with an even index in the array and grey to the odd indices.

Adding <th>'s to Vaadin Grid Dynamically

When adding columns dynamically how can I set the <th>'s in a grids header.
<vaadin-grid id="grid">
<table>
<colgroup>
</colgroup>
<thead>
<tr>
<th>adfdfa</th>
<th>adfdfa</th>
</tr>
</thead>
</table>
</vaadin-grid>
_addCols: function() {
var inputs = this.selectedForm.inputs;
var grid = this.$.grid;
grid.columns = [];
for(var i = 0; i < inputs.length; i++) {
var input = inputs[i];
grid.addColumn({name: input.$key}, i);
}
},
No matter found this in the docs.
grid.header.getCell(0, 0).content = 'Project Name';
Documentation