I have a problem in displaying the borders of my table correctly ,I work with jsPDF library ,this is the result that I get :
this is my code that selecet every row and display the data:
function tableToJson(table) {
var data = [];
// first row needs to be headers
var headers = [];
for (var i=0; i<table.rows[0].cells.length,i<5; i++) {
headers[i] = table.rows[0].cells[i].innerHTML.toLowerCase().replace(/ /gi,'');
}
data.push(headers);
// go through cells
for (var i=1; i<table.rows.length;i++) {
var tableRow = table.rows[i];
var rowData = {};
for (var j=0; j<tableRow.cells.length,j<5 ; j++) {
rowData[ headers[j] ] = tableRow.cells[j].innerHTML;
}
data.push(rowData);
}
return data;
}
function callme(){
var table = tableToJson($('#table').get(0));
var doc = new jsPDF('l','pt','letter',true);
$.each(table, function(i, row){
$.each(row, function(j,cell){
if(j=="email"){
doc.cell(1,10,190,20,cell,i);
}
else{
doc.cell(1,10,100,20,cell,i);
}
});
});
thanks for help
Related
All, I have a module to import CSV file and fetch data and display in a grid. Fetched the data in array but I expected value must be in a particular JavaScript data structure.
Here my sample code
function processData(allText) {
var allTextLines = allText.split(/\r\n|\n/);
var headers = allTextLines[0].split(',');
console.log("headers-->"+headers)
var lines = [];
for (var i=1; i<allTextLines.length; i++) {
var data = allTextLines[i].split(',');
if (data.length == headers.length) {
var tarr = [];
for (var j=0; j<headers.length; j++) {
tarr.push(headers[j]+":"+data[j]);
}
lines.push(tarr);
// console.log(lines)
}
}
console.log("details ="+lines)
});
allText Value
serial,Asset Type,id
Asset1,Equipemnt,id1
Asset2,Equipemnt,id2
Asset3,Equipemnt,id3
Asset4,Equipemnt,id4
My output:
Serial:Asset1,Asset Type:Equipment,id:RF0001,
Serial:Asset2,Asset Type:Equipment,id:R0002,
Serial:Asset3,Asset Type:Equipment,id:R0003,
Serial:Asset4,Asset Type:Equipment,id:F0004,
Serial:Asset5,Asset Type:Equipment,id:F0005,
Serial:Asset6,Asset Type:Equipment,id:0006,
Serial:Asset7,Asset Type:Equipment,id:007,
Expected structure:
{
serial:["Asset1","Asset1","Asset2","Asset3","Asset4"],
Asset Type:["Equipment","Equipment","Equipment","Equipment","Equipment"],
id:["id1","id2","id3","id4",]
}
How to achieve this structure?
function processData(allText) {
var allTextLines = allText.split(/\r\n|\n/);
var headers = allTextLines[0].split(',');
console.log("headers-->"+headers)
//initializing resulting json
var lines = {};
//initializing arrays for all the headers
for(var i=0; i<headers.length; i++){
lines[headers[i]] = [];
}
for (var i=1; i<allTextLines.length; i++) {
var data = allTextLines[i].split(',');
if (data.length == headers.length) {
for (var j=0; j<headers.length; j++) {
lines[headers[j]].push(data[j]);
}
}
}
return lines
}
//format all text is taken up (I tested on a string)
allText = "serial,Asset Type,id\n Asset1,Equipemnt,id1\nAsset2,Equipemnt,id2\nAsset3,Equipemnt,id3\nAsset4,Equipemnt,id4"
Result :
You first line is header and wanted to set as a key object . So you already get that var headers = allTextLines[0].split(','); thus assign that object key by object[key] = value format .
I assume that your header and lines splited key has the same thus I loop allTextLines and used the same key for both headers and allTextLines !!
var all = "serial,Asset Type,id \n"+
"Asset1,Equipemnt,id1 \n"+
"Asset2,Equipemnt,id2 \n"+
"Asset3,Equipemnt,id3 \n"+
"Asset4,Equipemnt,id4";
processData(all);
function processData(allText) {
var allTextLines = allText.split(/\r\n|\n/);
var headers = allTextLines[0].split(',');
var lines = {};
//set headers as key
for(var i = 0 ; i < headers.length;i++) {
lines[headers[i]] = [];
}
//assign relative value to key
for (var i=1; i<allTextLines.length; i++) {
var data = allTextLines[i].split(',');
for(var d in data) {
lines[headers[d]].push(data[d]);
}
}
console.log(lines)
}
I have a function building a dynamic table. I'm having trouble figuring out how to set each column to a different data set from the database. Right now it just shows the same value in each column.
A little background. I'm building a table with 6 columns and lots of rows (all depends how much data the database has). Right now it's only showing one column in all of the 6 columns, so they repeat.
How can I set each column to a different value for the 6 columns?
function addTable() {
var len = errorTableData.length;
var myTableDiv = document.getElementById("myDynamicTable");
var table = document.createElement('TABLE');
table.border='1';
table.id = "dataTable";
var tableBody = document.createElement('TBODY');
table.appendChild(tableBody);
for (var i=0; i<len; i++){
var tr = document.createElement('TR');
tr.className = "rowEditData";
tableBody.appendChild(tr);
for (var j=0; j<6; j++){
var countyName = errorTableData['CountyName'][i];
var stateName = errorTableData['StateName'][i];
var td = document.createElement('TD');
td.className = "mdl-data-table__cell--non-numeric";
td.appendChild(document.createTextNode(countyName));
td.appendChild(document.createTextNode(stateName));
tr.appendChild(td);
}
}
myTableDiv.appendChild(table);
}
Here is the ajax call:
function triggerDataTable(index) {
// Make AJAX requests for model systems
$.ajax({
type: "POST",
url: "qry/getAllData.php",
async: true,
dataType: "html",
data: {ErrorOptions: control.settings.errorOptions},
success: function (result) {
//console.warn(result);
errorData = JSON.parse(result);
//loop through data
var len = errorData.length;
for(i=0; i<len; i++) {
if ('VersionKey' in errorData[i]) {
vKey = (errorData[i]['VersionKey']);
} else if ('ErrorCode' in errorData[i]) {
var errorCode = (errorData[i]['ErrorCode']);
} else if ('SourceKey' in errorData[i]) {
var sourceKey = (errorData[i]['SourceKey']);
} else { //data here
errorTableData = errorData[i];
}
}
addTable();
}
});
}
The errorData is the data from the database. As you can see I've tried to add 2 variables but when I do that it just puts both of them in the same box and repeats throughout the whole table.
It looks like you are printing the exact same data 6 times for each row. You create a td element, then add country and state names to it, but the variable you are using for the index on your data set is coming from your outer loop, so on the inner loop it never changes, and you are literally grabbing the same value every time:
function addTable() {
var len = errorTableData.length;
var myTableDiv = document.getElementById("myDynamicTable");
var table = document.createElement('TABLE');
table.border='1';
table.id = "dataTable";
var tableBody = document.createElement('TBODY');
table.appendChild(tableBody);
for (var i=0; i<len; i++){
// You set i here, presumably to get each row in your dataset
var tr = document.createElement('TR');
tr.className = "rowEditData";
tableBody.appendChild(tr);
for (var j=0; j<6; j++){
var countyName = errorTableData['CountyName'][i];
var stateName = errorTableData['StateName'][i];
// Above, you are using i, not j
var td = document.createElement('TD');
td.className = "mdl-data-table__cell--non-numeric";
td.appendChild(document.createTextNode(countyName));
td.appendChild(document.createTextNode(stateName));
tr.appendChild(td);
}
}
myTableDiv.appendChild(table);
}
It would be easier to help if you could post some json with the data you are getting from the DB
Based on the edit on your post and looking at the success callback, I think you have small problem that can be easily fixed:
First, initialize an empty array for errorTableData
success: function (result) {
errorTableData = [];
In your if/else block:
} else { //data here
errorTableData = errorData[i];
}
Should be:
} else { //data here
errorTableData[i] = errorData[i];
}
Then in your inner loop:
var countyName = errorTableData['CountyName'][i];
var stateName = errorTableData['StateName'][i];
Becomes:
var countyName = errorTableData[i]['CountyName'][j];
var stateName = errorTableData[i]['StateName'][j];
This is just a guess because I can't see the actual data.
List<Object1> list = new ArrayList<>();
List<Object2> list = new ArrayList<>();
ADD LIST button is for add the code and value to the textbox as show below.
ADD button is to add the all input data into the table below.
DELETE button is for delete from table
SUBMIT button is for post to server.
So what I have trying to do is
For button Add not Add List <- No idea for this at all!
function Add() {
var url = "/root/info/add&"+$("#fieldrows").serialize();
uField(url);
return false;
}
function uField(url) {
$.ajax({
type: 'GET'
url: url,
async: false,
success: function(data) {
try {
var res = eval("("+data+")");
if (res.success) {
var content="";
$.each(res.result, function(i, f) {
content+=addRow((i%2==1),f.seq,f.name,....);
});
$("#fieldrows").find("tbody").html(content);
bindFieldLink();
} else {
alert(res.error);
}
}catch(e) {}
}
});
}
function addRow(odd, seq,name,...) {
var oddS = "odd";
if (!odd) { oddS = "even"; }
var style="";
var seq="<a id='field_id_"+seq+"' class='fLink' href='#'>"+label+"</a>";
var row = "<tr class='"+oddS+"'><td class='chk'><input type='checkbox' seq='ids' value='"+seq+"' class='checkbox'></td>";
row += "<td>"+seq+"</td>";
row += "<td>"+rexp+"</td>";
row +="</tr>";
return row;
}
Call the function to call to server via ajax, not sure what is .serialize() for url
At server it return as JSON, I am new to this also.
After that build html for result table. But I am not sure what is bindFieldLink().
Someone please help. I am using JAVA, Spring MVC. Thank you so much.
This post can be close.
var myJson = [{"name" : "abc", "age" : 50},
{"age" : "25", "hobby" : "swimming"},
{"name" : "xyz", "hobby" : "programming"}];
// Builds the HTML Table out of myList.
function buildHtmlTable(selector) {
var columns = addAllColumnHeaders(myList, selector);
for (var i = 0 ; i < myJson.length ; i++) {
var row$ = $('<tr/>');
for (var colIndex = 0 ; colIndex < columns.length ; colIndex++) {
var cellValue = myList[i][columns[colIndex]];
if (cellValue == null) { cellValue = ""; }
row$.append($('<td/>').html(cellValue));
}
$(selector).append(row$);
}
}
// Adds a header row to the table and returns the set of columns.
// Need to do union of keys from all records as some records may not contain
// all records
function addAllColumnHeaders(myList){
var columnSet = [];
var headerTr$ = $('<tr/>');
for (var i = 0 ; i < myList.length ; i++) {
var rowHash = myList[i];
for (var key in rowHash) {
if ($.inArray(key, columnSet) == -1){
columnSet.push(key);
headerTr$.append($('<th/>').html(key));
}
}
}
$(selector).append(headerTr$);
return columnSet;
}
HTML:
<body onLoad="buildHtmlTable('#excelDataTable')">
<table id="excelDataTable" border="1">
</table>
</body>
Hello I try to generate an HTML Table with two arrays. Where one array is for the Headers and the other one is for the rows. The arrays work like a blast but the generation of the HTML-Table wont work.....
Here is my little Function: (For the arrays and they work like a blast)
function loadDepartments() {
var query = "$select=DepartmentID,WEBName";
getListItems("example.at", "WEBepartments", query, function (results) {
results.forEach(function (result) {
departments.push({
name: result.WEBName,
id: result.DepartmentID
});
});
loadCountries();
},
function (error) {
console.log(error);
});
}
function loadCountries() {
var query = "$select=CountryID,WEBName,Acronym";
getListItems("https://intranet.windkraft.at/", "WEBCountries", query, function (results) {
results.forEach(function (result) {
countries.push({
name: result.WEBName,
id: result.CountryID,
acronym: result.Acronym
});
});
doNextSteps();
},
function (error) {
console.log(error);
});
}
And here my latest Try:
function doNextSteps() {
//Create a HTML Table element.
var table = document.createElement("TABLE");
table.border = "1";
//Get the count of columns and rows.
var columnCount = departments.length;
var rowCount = countries.length;
//Add the header row.
var row = table.insertRow(-1);
for (var i = 0; i < columnCount; i++) {
var headerCell = document.createElement("TH");
headerCell.innerHTML = columnCount[0];
row.appendChild(headerCell);
}
//Add the data rows.
for (var i = 1; i < countries.length; i++) {
row = table.insertRow(-1);
for (var j = 0; j < rowCount; j++) {
var cell = row.insertCell(-1);
cell.innerHTML = rowCount[0];
}
}
var dvTable = document.getElementById("dvTable");
dvTable.innerHTML = "";
dvTable.appendChild(table);
}
But wont work the only thing i get is nothing or undefined. And i have no clue why becouse its the first time i try to generate a HTML Table with javascript. So any help would be great.
Thx for your Time and Help.
I am developing a simple add-on with Firefox SDK that allows the user to review the stored data.
I would like to show the items in a panel with a table. The table is created dynamically with the data incoming from the data-base. Firstly, In the JavaScript code I create the items with their properties, then I create a table with the properties as row and I append the items with the value of each properties.
I have some problems: the table has only the item's name as first row and the properties name as first column without the value in the cells. It seems that the code is not executed in order, but it seems that the faster functions are executed first.
This is the code:
self.on('message', function() {
var container = $('#container');
container.empty();
items = [];
self.port.emit('getItem');
});
self.port.on('items', function(response) {
var ok = 0;
var items = [];
var table = $('#tableContainer #table').clone();
var container = $('#container');
table.append("<tr id=first><th> </th></tr>");
var json = eval('('+ response + ')');
for (var i = 0, len = json.length; i < len; ++i) {
var item = {
id: json[i],
properties: []
};
items.push(item);
}
items.forEach ( function(item) {
table.find('#first').append("<th id="+item.id+">"+item.id+"</th>");
self.port.emit('detailsItem', item.id);
self.port.on('details'+item.id, function(response) {
var details = eval('('+ response + ')');
var description = [];
ndet = details.length;
var len = details.length;
for (var i = 0; i < len;) {
var detail = {
dimension : details[i].dimension,
value : details[i].value
}
description.push(detail);
++i;
}
item.properties = description;
});
});
self.port.emit('getDimension');
self.port.on('dimension', function(response) {
var dimensions = eval('('+ response + ')');
for(var cont = 0, l = dimensions.length; cont < l; ++cont) {
table.append("<tr id=dimension"+cont+"><td>"+dimensions[cont]+"</td></tr>");
items.forEach( function(item) {
var prop = [];
prop = item.properties;
var lun = prop.length;
for( var p =0;p < lun;) {
if(item.properties[p].dimension == dimensions[cont]) { table.find('#dimension'+cont).append("<td>"+item.properties[p].value+"</td>");
}
else {
table.find('#dimension'+cont).append("<td> --- </td>");
}
++p; }
});
};
});
container.append(table);
});